List compreension vs ciclo for

Asked

Viewed 123 times

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 use one to the detriment of another? Or is it indifferent? Why?

  • It depends. On what aspect?

  • Performance/feasibility e.g. In this very one. Which would you choose? Advantages and disadvantages

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)

Using the "time" command (ex: time python script.py) and extrapolating the size of the list from 50 to 500,000 is possible to get an idea that the first method is faster. However for only 50 iterations I believe it can be said that the difference is marginal.

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

  • Thank you. +1 by the command I didn’t know time python file.py

Browser other questions tagged

You are not signed in. Login or sign up in order to post.