The goal of this post is to put multiple print functions throughout a list comprehension to visually understand what's happening within.
Important notes:
- This should not be used for anything other than educational purposes and trying to understand code.
- If you are using Python 2.x, you need to add a future import (it's in the code I pasted) or else print won't work. Only functions work in list comprehension. Print in 2.x does not operate as a function. Or...just switch to Python 3.x.
This was the original question:
## Using future to switch Print to a function
from __future__ import print_function
reg = []
for x in [1,2,3]:
for y in [3,1,4]:
print('looping through',x,'then',y)
if x == y:
print('success',x,y)
reg.append((x,y))
print(reg)
Here's the equivalent list comprehension with no print statements.
from __future__ import print_function
comp = [(x,y) for x in [1,2,3] for y in [3,1,4] if x == y]
print(comp)
So is there any way to put in a bunch of print statements so both code print the same things?
Edit with solution to original question:
Using the methods in the comments - I've figured it out!
So say you want to convert this.
from __future__ import print_function
x = 1
y = 2
z = 1
n = 2
[[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n]
Adding print statements to print each loop, showing if it failed or not.
from __future__ import print_function
x = 1
y = 2
z = 1
n = 2
[
[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if
(print('current loop is',a,b,c) or a + b + c != n)
and
(print('condition true at',a,b,c) or True)
]
So really the only thing that was changed was the conditional at the end.
(a + b + c != n)
to
(print('current loop is',a,b,c) or a + b + c != n)
and
(print('condition true at',a,b,c) or True)
Additional Information:
So there's good stuff in the comment section that I think would help others as well. I'm a visual learner so this website was great.
(credits to Tadhg McDonald-Jensen)