[Python] Why is my Python list comprehension returning unexpected results [closed]

Discussão em 'Python' iniciado por Stack, Março 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use a list comprehension to filter and transform a list of numbers, but the output isn't what I expect. Here's a simplified example:

    numbers = [1, 2, 3, 4, 5]
    squared_evens = [x**2 for x in numbers if x % 2 == 0]
    print(squared_evens) # Actual output: [4, 16] (expected [4, 16, 25])


    I expected the comprehension to square all even numbers (2, 4) and include 25 (since 5 is odd but I want to include it). How can I modify the comprehension to get square even numbers and keep odd numbers unchanged.

    I have tried to add an else clause like [x**2 if x % 2 == 0 else x for x in numbers], but this doesn’t filter odds.

    And I also used a nested ternary, but it got messy.

    Desired output: [1, 4, 3, 16, 5]

    Is there a clean and Pythonic way to achieve this?

    Continue reading...

Compartilhe esta Página