Search code examples
pythonpython-3.xlistfunctionlist-comprehension

Using multiple conditional expressions within list comprehension


I am writing a program to evaluate range(1, 10) which should return divisible by 3 and even if a number is divisible by 3 and even.

If the the number is even and not divisible by 3 then it should return even.

Otherwise it should return odd.

I need to use list comprehension to evaluate multiple conditional expressions.

My program looks as below:

l = list(zip(
            range(1, 10),
            ['even and divisible by 3' if x%3 == 0 else 'even' if x%2 == 0 else 'odd' for x in range(1, 10)]
             ))

print(l)

Output:

[(1, 'odd'), (2, 'even'), (3, 'even and divisible by 3'), (4, 'even'), (5, 'odd'), (6, 'even and divisible by 3'), (7, 'odd'), (8, 'even'), (9, 'even and divisible by 3')]

I am not able to understand why program is giving (3, 'even and divisible by 3'). This is because, x%2 == 0 else 'odd' is evaluated first which should return odd


Solution

  • There are two different ways to group the expressions. Consider adding parentheses for clarity:

    >>> x = 3
    >>> 'even and divisible by 3' if x%3 == 0 else ('even' if x%2 == 0 else 'odd')
    'even and divisible by 3'
    >>> ('even and divisible by 3' if x%3 == 0 else 'even') if x%2 == 0 else 'odd'
    'odd'