jhub1 jhub1 - 1 year ago 81
Python Question

Multiple print functions in list comprehension

So there are multiple variations of this question but none of them quite answer my question.

My goal is to put multiple statements throughout a list comprehension to visually understand what's happening within. I'm using other methods to understand complex list comprehension's, but it'd be nice to know if this is possible.

I'm not actually using this to write list comprehension's - this is for reading and understanding complex code written by advanced coders.

For other beginners, I'm using future import because print needs to be a function for it to work in list comprehension. That will only work in 3.x Python.

Here's a simple, nested loop with a bunch of prints.

## 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:

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]

So is there any way to put in a bunch of print statements so both code print the same things?


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 something I've been hoping to find for ages!

(credits to Tadhg McDonald-Jensen)

Answer Source

I think you shouldn't running debug code inside list comprehensions, that said, if you wanted to do so, you could wrap your code inside a function like this:

from __future__ import print_function

def foo(x, y):
    print('looping through', x, 'then', y)
    if x == y:
        print('success', x, y)
        return (x, y)

comp = [foo(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x == y]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download