Unexpected result with Python list comprehension

Soldato
Joined
26 Oct 2002
Posts
3,676
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?
 
Associate
Joined
10 Nov 2006
Posts
1,859
Location
Lincoln
Hi R4z0r,

I'm new to this too, so couldn't tell you exactly what is wrong with your code, however, my IDLE (python 3.6, hence the brackets in the call to print) suggests that you have not defined n and that there is a traceback.

I have written a script which does what you would like it to as below:

Code:
nums = [1, 2, 3, 4, 5, 6]

print(nums)

evn_sqr = []

def even_squares(nums):
    for n in nums:
        sqr = n ** 2
        if sqr % 2 == 0:
            evn_sqr.append(sqr)
    print(evn_sqr)
            
even_squares(nums)

This outputs:

[1, 2, 3, 4, 5, 6]
[4, 16, 36]

i created a list evn_sqr to store the squares of the numbers in nums and then used an if statement to only store the even numbers in it.

I hope this helps!

Jonny L
 
Associate
Joined
16 Oct 2006
Posts
560
Location
U.K.
Quite surprised your repl isn't throwing a fit.

As above, n isn't defined. While the above may work, to achieve the same using comprehensions (as per your post) you need to have something like:

Code:
even_squares = [n * n for n in nums if n % 2 == 0]

Where n is defined in the for construct.
 
Back
Top Bottom