Siwel Siwel - 4 months ago 8
Python Question

Using comprehensions instead of a for loop

The following is a simplified example of my code.

>>> def action(num):
print "Number is", num
>>> items = [1, 3, 6]
>>> for i in [j for j in items if j > 4]:
action(i)
Number is 6


My question is the following: is it bad practice (for reasons such as code clarity) to simply replace the
for
loop with a comprehension which will still call the
action
function? That is:

>>> (action(j) for j in items if j > 2)
Number is 6

Answer

This shouldn't use a generator or comprehension at all.

def action(num):
    print "Number is", num

items = [1, 3, 6]
for j in items:
    if j > 4:
        action(i)

Generators evaluate lazily. The expression (action(j) for j in items if j > 2) will merely return a generator expression to the caller. Nothing will happen in it unless you explicitly exhaust it. List comprehensions evaluate eagerly, but, in this particular case, you are left with a list with no purpose. Just use a regular loop.