0
0
Pythonprogramming~20 mins

len() function in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Len Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of len() with nested lists
What is the output of the following code?
Python
lst = [1, [2, 3], 4]
print(len(lst))
A3
B4
C2
D5
Attempts:
2 left
๐Ÿ’ก Hint
len() counts the top-level items in the list.
โ“ Predict Output
intermediate
2:00remaining
Length of a string with spaces
What will be printed by this code?
Python
text = 'Hello World'
print(len(text))
A9
B10
C12
D11
Attempts:
2 left
๐Ÿ’ก Hint
Spaces count as characters in strings.
โ“ Predict Output
advanced
2:00remaining
Length of dictionary keys
What is the output of this code?
Python
d = {"a": 1, "b": 2, "c": 3}
print(len(d.keys()))
ATypeError
B0
C3
D1
Attempts:
2 left
๐Ÿ’ก Hint
len() counts how many keys are in the dictionary.
โ“ Predict Output
advanced
2:00remaining
len() on a generator expression
What happens when you run this code?
Python
gen = (x for x in range(5))
print(len(gen))
A5
BTypeError
C0
DAttributeError
Attempts:
2 left
๐Ÿ’ก Hint
Generators do not have a length.
โ“ Predict Output
expert
2: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))
A5
B3
C0
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
The __len__ method sums lengths of inner lists.