[Python] Why does my Python list comprehension with conditional logic return unexpected...

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create a list of squares of even numbers from an existing list, but my list comprehension is returning some odd squares as well. Here's a minimal example:

    numbers = [1, 2, 3, 4, 5, 6]
    result = [n**2 for n in numbers if n % 2 == 0 else n for n in numbers]
    print(result)


    I expected the result to be [4, 16, 36] (i.e., squares of 2, 4, and 6), but instead I'm seeing:

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


    What I've tried so far:

    • Checked my indentation and placement of if/else clauses in the comprehension.
    • Tried splitting into a regular for loop:
      result = []
      for n in numbers:
      if n % 2 == 0:
      result.append(n**2)
      print(result)

      This works correctly (yields [4, 16, 36]), so I know the logic itself is fine.
    • Googled "Python list comprehension if else order" and reviewed documentation, but I still can't get the syntax right.

    Why is my comprehension returning [1, 4, 3, 16, 5, 36] instead of just even squares? How do I write a correct list comprehension to achieve [n**2 for n in numbers if n % 2 == 0]?

    Continue reading...

Compartilhe esta Página