user93 user93 - 2 years ago 68
Python Question

conversion of multiple line into list comphrension python

I have python code similar to the following

for a in range(0,x):
if a%2==0:

could it be converted into list comprehensions or is there other way to reduce it.

Answer Source

The generation of the list can be converted into a list comprehension, but the print statements cannot be done in one line:

x = 10
l1 = [a for a in range(0, x) if a % 2 == 0]

Will give you the list, if you want also the print statements, more work is needed, e.g. define a function that is called while the list is built:

def foo(a):
    return a

l2 = [a for a in range(0, x) if foo(a) % 2 == 0]

This latter option is however "a code smell", generating a list while relying for output on the side-effect of a function is not a good practice (very error prone in an even moderately large program). I would not recommend the latter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download