List comprehension vs cycle for

4

I have the following code segments:

def is_even(num):
    if(num % 2 == 0):
        return True
    return False

1.

lista = range(50)
pares = [i for i in lista if is_even(i)]
# pares = [0, 2, 4, 6, 8...]

2.

lista = range(50)
pares = []
for i in lista:
    if is_even(i):
        pares.append(i)
# pares = [0, 2, 4, 6, 8...]

In this case, should one be used over another? Or is it indifferent? Why?

    
asked by anonymous 27.05.2016 / 20:07

1 answer

2

Testing with the first script:

def is_even(num):
    if(num % 2 == 0):
        return True
    return False

lista = range(5000000)
pares = [i for i in lista if is_even(i)]

And with the second script:

def is_even(num):
    if(num % 2 == 0):
        return True
    return False

lista = range(5000000)
pares = []
for i in lista:
    if is_even(i):
        pares.append(i)

By using the "time" command (ex: time python script.py ) and extrapolating the list size value from 50 to 5000000 you can get an idea that the first method is faster. However for only 50 iterations I believe one can say that the difference is marginal.

The code of the first solution also seems more elegant and better read.

    
27.05.2016 / 21:41