Challenge - 5 Problems
Len Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of len() with nested lists
What is the output of the following code?
Python
lst = [1, [2, 3], 4] print(len(lst))
Attempts:
2 left
๐ก Hint
len() counts the top-level items in the list.
โ Incorrect
The list has three top-level elements: 1, [2, 3], and 4. So len(lst) is 3.
โ Predict Output
intermediate2:00remaining
Length of a string with spaces
What will be printed by this code?
Python
text = 'Hello World' print(len(text))
Attempts:
2 left
๐ก Hint
Spaces count as characters in strings.
โ Incorrect
The string 'Hello World' has 11 characters including the space.
โ Predict Output
advanced2:00remaining
Length of dictionary keys
What is the output of this code?
Python
d = {"a": 1, "b": 2, "c": 3}
print(len(d.keys()))Attempts:
2 left
๐ก Hint
len() counts how many keys are in the dictionary.
โ Incorrect
d.keys() returns a view of the keys, which has length 3.
โ Predict Output
advanced2:00remaining
len() on a generator expression
What happens when you run this code?
Python
gen = (x for x in range(5)) print(len(gen))
Attempts:
2 left
๐ก Hint
Generators do not have a length.
โ Incorrect
Calling len() on a generator raises a TypeError because generators do not support len().
โ Predict Output
expert2:00remaining
Length of a custom class with __len__
What will this code print?
Python
class Box: def __init__(self, items): self.items = items def __len__(self): return sum(len(item) for item in self.items) b = Box([[1, 2], [3, 4, 5], []]) print(len(b))
Attempts:
2 left
๐ก Hint
The __len__ method sums lengths of inner lists.
โ Incorrect
The Box contains three lists with lengths 2, 3, and 0. Their sum is 5.