Unexpected result with Python list comprehension

Soldato
Joined
26 Oct 2002
Posts
3,700
Location
Surrey
Hi All,

I am quite new to programming and have been playing with Pythons list comprehension feature. I executed the following code and got an unexpected result.

Code:
>>> nums = [1, 2, 3, 4, 5, 6]
>>> print nums
[1, 2, 3, 4, 5, 6]
>>> even_squares = [n * n for num in nums if num % 2 == 0]
>>> print even_squares
[36, 36, 36]

I expected even_squares to simply hold a list of the squares for the 3 even numbers. Instead, it just holds the square of 6 three times.

I expect there is a very simple explanation for this and I am kicking myself for not seeing it. Can anyone help?
 
Back
Top Bottom