Why is there a word in front of the for loop here?

Issue

I’m relatively new to python and I saw this code to check for an even number, specifically tasked to use one line of code when creating a list and sorting even numbers into it.

I’m used to seeing:

for item in list: # etc etc

But why is there another num, in front of the for loop here:

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
even_numbers = [num for num in a if num % 2 is 0] # on this line
print(even_numbers)

Solution

[num for num in a if num % 2 is 0]

In Python this is known as a "list comprehension." Its a short hand way of implementing the following code:

even_numbers = []
for num in a:
    if num % 2 == 0:
        even_numbers.append(num)

Answered By – m_callens

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published