user93 user93 - 7 months ago 18
Python Question

conversion of multiple line into list comphrension python

I have python code similar to the following

for a in range(0,x):
print("test")
print("test2")
if a%2==0:
l1.append(a)


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

Answer

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):
    print('Test1')
    print('Test2')
    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.