Python comprehension with multiple prints

Question:

I want to put this for loop into a comprehension. Is this even possible?

for i in range(1, 11):
    result = len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})
    print(f'There are {result} different unique walks with length {i}')

I tried stuff like

print({tuple(walk) for i in range(1, 11)  for (walk, distance) in dic[i] if distance == 0})

but this prints all walks for all i together, but i want 10 different print statements.

Asked By: DaSomes

||

Answers:

You were pretty close actually:

[print(f'There are {len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})} different unique walks with length {i}') for i in range(1,11)]

But it’s a long and ugly oneliner, in a regular for loop it looks way better.

Answered By: Gameplay

Technically yes, but I’d not recommend doing that. You can actually use a list comprehension for that but it would really defy their purpose.

You can use functions in comprehensions, but usually their return values is accumulated in the structure. Since the print function doesn’t return a value (None), such a comprehension would accumulate a series of Nones, which is not very pythonic.

>>> res = [print(i) for i in range(1, 11)]
1
2
...
>>> res
[None, None, ...]

Much better is to collect all the lines you want to print and concatenate them together (for example using str.join or unpacking them into print):

>>> print('n'.join(str(i) for i in range(1, 11)))
1
2
...

or

>>> res = [i for i in range(1, 11)]
>>> res
[1, 2, ...]
>>> print(*res, sep='n')
1
2
...
Answered By: Lone Lunatic