montymagic9 montymagic9 -4 years ago 80
Python Question

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

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)

Answer Source

[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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download