Challenge - 5 Problems
Master of List Iteration
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested loops with list iteration
What is the output of this Python code?
Python
result = [] for i in [1, 2]: for j in [3, 4]: result.append(i * j) print(result)
Attempts:
2 left
💡 Hint
Think about how the outer and inner loops multiply each pair of numbers.
✗ Incorrect
The outer loop goes over 1 and 2. For each, the inner loop multiplies by 3 and 4. So the products are 1*3=3, 1*4=4, 2*3=6, 2*4=8, collected in order.
❓ Predict Output
intermediate2:00remaining
Output of list comprehension with condition
What is the output of this code?
Python
numbers = [0, 1, 2, 3, 4] squares = [x**2 for x in numbers if x % 2 == 0] print(squares)
Attempts:
2 left
💡 Hint
Only even numbers are squared and included.
✗ Incorrect
The list comprehension squares only numbers divisible by 2: 0, 2, and 4. Their squares are 0, 4, and 16.
🔧 Debug
advanced2:00remaining
Identify the error in list iteration
What error does this code raise when run?
Python
items = [1, 2, 3] for i in range(len(items)): print(items[i+1])
Attempts:
2 left
💡 Hint
Check the index used inside the loop compared to the list length.
✗ Incorrect
The loop tries to access items[i+1]. When i is 2 (last index), i+1 is 3, which is out of range for the list of length 3, causing IndexError.
❓ Predict Output
advanced2:00remaining
Output of modifying list during iteration
What is the output of this code?
Python
lst = [1, 2, 3] for x in lst: lst.append(x + 3) if len(lst) > 6: break print(lst)
Attempts:
2 left
💡 Hint
Appending to a list during 'for x in lst' iteration only processes the original elements; the break checks length after each append.
✗ Incorrect
The 'for x in lst' iterates over the list as it grows. For x=1, append 4 (len=4 <=6); x=2, append 5 (len=5 <=6); x=3, append 6 (len=6 <=6). After appending 6, length becomes 7 (>6), so break triggers. Final list: [1, 2, 3, 4, 5, 6, 7].
🧠 Conceptual
expert2:00remaining
Number of items after complex iteration
How many items are in the list 'result' after running this code?
Python
result = [] for i in range(3): for j in range(i): result.append(i + j) print(len(result))
Attempts:
2 left
💡 Hint
Count how many times the inner loop runs for each i.
✗ Incorrect
For i=0, inner loop runs 0 times; i=1 runs 1 time; i=2 runs 2 times. Total items appended: 0 + 1 + 2 = 3.