0

Why this does not work?

[ print("%d03" % a) for a in range(1,99)]
  File "<stdin>", line 1
    [ print("%d03" % a) for a in range(1,99)]
          ^
SyntaxError: invalid syntax

but

print("%03d" % a)
098

0

4 Answers 4

5

In Python 2.x, print is a statement, so it cannot appear as part of an expression. In Python 3.x, the list comprehension would be syntactically correct because print was turned into a function, though a bit pointless since print() always returns None.

In any case, this is the right way to do it:

for a in range(1,99):
    print("%d03" % a)
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure why you can't use print in a list comprehension, but you can work around it:

In: print ["%03d" % a for a in range(1,10)]
['001', '002', '003', '004', '005', '006', '007', '008', '009']

Comments

0
print('\n'.join(['%d03' % i for i in range(1,99)]))

print doesn't return anything so you can't use it in an expression.

Comments

0

This is because print() is a function that prints the arguments, but does not return them. Good news is that you don't need print() for formatting.

What you (probably) are looking for is:

["%03d" % a for a in range(1,99)]

or using the built in function format():

[format(a, "03d") for a in range(1,99)]

If you indeed want to print() the numbers, then don't use list comprehension, but just a simple for loop:

for _ in range(99): print("%03d" % _)

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.