pythonintermediate10 minutes

Predict the Output of Nested List Comprehensions with Conditional Logic

Analyze nested list comprehensions with conditional statements and predict the final output of the given Python code snippet.

Challenge prompt

Consider the following Python code that uses nested list comprehensions combined with conditional and arithmetic logic. Predict the exact output printed by the code: for i in range(3): result = [j * i if j % 2 == 0 else j + i for j in range(5)] print(result) What is the output of the above code?

Guidance

  • Carefully evaluate the nested list comprehension inside the loop for each value of i from 0 to 2.
  • For each element j in the inner range, decide which expression applies based on whether j is even or odd.
  • Calculate the final derived list for each iteration and consider how the results change with different values of i.

Hints

  • Recall that 'j % 2 == 0' checks if j is even.
  • For even j, the expression is 'j * i'; for odd j, it is 'j + i'.
  • Track the values of i and j step-by-step for clarity.

Starter code

for i in range(3):
    result = [j * i if j % 2 == 0 else j + i for j in range(5)]
    print(result)

Expected output

[0, 1, 0, 3, 0] [0, 2, 2, 4, 4] [0, 3, 4, 5, 8]

Core concepts

list comprehensionsconditional expressionsloopsmodulo operator

Challenge a Friend

Send this duel to someone else and see if they can solve it.