Python Forum

Full Version: Problem with List Comprehension in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,
I’m working on a Python project where I need to filter and transform a list of numbers. I want to create a new list that contains the squares of all even numbers from the original list. However, my current code is not working as expected.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Attempt to use list comprehension to filter and square even numbers
squared_evens = [x**2 for x in numbers if x % 2 != 0]

print(squared_evens)
The output of the code is [1, 9, 25, 49, 81], but I expected it to be [4, 16, 36, 64, 100].
Why is my list comprehension not working correctly?
How can I fix it to get the squares of even numbers?
Thanks in advance for your help!
The remainder of even numbers divided by 2 == 0
You're filtering to keep the _odd_ numbers, not the even ones.
Having a distracted day?

nums = [x for x in range(11) if x != 0]        
evens = [x for x in nums if x % 2 == 0]
odds = [x for x in nums if x % 2 != 0]