Search code examples
pythonlist-comprehension

Multiple if statements in list comprehension with one iterator


I was studying list comprehension and came across the possibility of adding several conditions. I do not know what behavior I expected, but I cannot explain what I am getting. Why does 1 turn into 3, 2 remains a 2, and 3 turns into 6?

a = [x if x % 2 == 0 else x * 2 if x % 3 == 0 else x * 3 for x in range(1, 11)]

output:

[3, 2, 6, 4, 15, 6, 21, 8, 18, 10]

Solution

  • Re-writing as a loop and converting the conditional expressions to full if/elif/else statements might help explain it:

    a = []
    for x in range(1, 11):
        if x % 2 == 0:
            temp = x
        elif x % 3 == 0:
            temp = x * 2
        else:
            temp = x * 3
        a.append(temp)