3

I have this piece of code in python 3:

i=0
for item in splitDict(Team, 3):
    i+=1
    print("{1} #{0}".format(i,item))

What I'd like to do is:

i=0
for item in splitDict(Team, 3):
    print("{1} #{0}".format(i+=1,item))

Notice I've put the increment into the format statement. But when I run it I get the error:

print("{1} #{0}".format(i+=1,item))
                              ^
SyntaxError: invalid syntax

My question is how can I get it to increment in the print statement?

4
  • 1
    Why? Obscuring your code to save a line; you would have trouble finding a popular language where that is less idiomatic than python. Commented Apr 23, 2017 at 7:23
  • 1
    This seems like an xy problem Commented Apr 23, 2017 at 7:25
  • 1
    Just use enumerate and you don't have to increment manually. Commented Apr 23, 2017 at 7:25
  • 3
    Assignment in Python is not an expression but a statement in itself. You can't use it where you're trying to use it. Commented Apr 23, 2017 at 7:26

2 Answers 2

4

Clearly you are really wanting to use enumerate to solve your problem. But to answer the specific question of "how can I increment i within the print statement" ... then you can do the following very ugly thing (its not strictly within):

i=0
for item in splitDict(Team, 3):
    i += print("{1} #{0}".format(i + 1, item)) or 1

But you shouldn't. Use enumerate:

for i, item in enumerate(splitDict(Team, 3)):
    print("{1} #{0}".format(i, item))
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks. I'm at the beginning of my journey with python. Lessons liked this help mer understand what I should and shouldn't do.
0

sorry I couldn't get your original code working, this is the best I could come up with

splitDict = ['a','b','c','d','e']
x=0
for i,item in enumerate(splitDict, start=x):
    print ('#'+str(i),item)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.