Python List Comprehension Error: Unexpected Output

kulluM

New member
I'm encountering an unexpected output while using list comprehension in Python. I'm trying to create a list of squared values for even numbers in a given range, but the result is not what I anticipated. Here's the code I'm using:

Python:
even_numbers = [x for x in range(10) if x % 2 == 0]
squared_values = [x**2 for x in even_numbers]

print(squared_values)

I expected the output to be [0, 4, 16, 36, 64], but instead, I'm getting [0, 4, 16]. It seems like the last even number (8) and its corresponding squared value (64) are missing.

Can someone help me understand why this is happening and how to correct my list comprehension code to get the desired output? Is there something I'm overlooking in my approach? Your insights would be greatly appreciated. Thank you!
 

pix07

Well-known member
Works well on python 3.9.2 im adding screenshot:

Which version of python are you use ?

And add other numbers:

Im also give a code.

Code:
even_numbers=[x for x in range (10) if x %2 ==0]

numbers=[x for x in range (10) if x//2 !=0]

squared_values=[x**2 for x in even_numbers]

print(squared_values)

print(numbers)
 

Attachments

  • Zrzut ekranu z 2023-08-29 15-50-28.png
    Zrzut ekranu z 2023-08-29 15-50-28.png
    68.2 KB · Views: 0
  • Zrzut ekranu z 2023-08-29 15-55-05.png
    Zrzut ekranu z 2023-08-29 15-55-05.png
    59.8 KB · Views: 0
Last edited:
Top