0
0
Pythonprogramming~20 mins

Length and iteration methods in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Length and Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of length and iteration over a nested list
What is the output of this Python code?
Python
nested = [[1, 2], [3, 4, 5], []]
count = 0
for sublist in nested:
    count += len(sublist)
print(count)
ATypeError
B3
C0
D5
Attempts:
2 left
💡 Hint
Count the total number of elements inside all sublists.
Predict Output
intermediate
2:00remaining
Length of a dictionary after iteration
What is the output of this code snippet?
Python
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
    d[key] += 1
print(len(d))
A3
B6
CTypeError
DKeyError
Attempts:
2 left
💡 Hint
Length of a dictionary counts keys, not values.
Predict Output
advanced
2:00remaining
Output of iteration with modification inside loop
What is the output of this code?
Python
lst = [1, 2, 3, 4]
for i in lst:
    lst.remove(i)
print(lst)
A[1, 3]
B[2, 4]
C[3, 4]
DRuntimeError
Attempts:
2 left
💡 Hint
Removing items while iterating changes the list length and indices.
Predict Output
advanced
2:00remaining
Length and iteration over a generator expression
What happens when you run this code?
Python
gen = (x for x in range(5))
print(len(gen))
A0
B5
CTypeError
DAttributeError
Attempts:
2 left
💡 Hint
Generators do not support len() because they produce items on the fly.
Predict Output
expert
3:00remaining
Final value after complex iteration and length checks
What is the value of variable 'result' after running this code?
Python
data = ['a', 'bb', 'ccc', 'dddd']
result = 0
for item in data:
    if len(item) % 2 == 0:
        result += len(item)
    else:
        result -= 1
print(result)
A4
B6
C-2
D5
Attempts:
2 left
💡 Hint
Add lengths of even-length strings, subtract 1 for odd-length strings.