Remember
len() returns the number of items in a sized object. For strings, it counts Unicode code points, not encoded bytes.
len() returns the number of items in a sized object. For strings, it counts Unicode code points, not encoded bytes.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = 'tea'
print(len(text))Top-level scope
'tea'len() returns the number of items in a sized object. For strings, it counts Unicode code points, not encoded bytes.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = 'tea'
print(len(text))
|
v
DISPLAYED RESULT
3
FINAL BINDINGS
text --> object 1 (str)
object 1: 'tea'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = 'tea'
print(len(text))Top-level scope
'tea'The example has finished. Compare the final output with the values and references above.
3
What do you expect this program to print?
text = 'tea'
print(len(text))len() FunctionThe len() function in Python is used to get the number of items in an object. It works with many data types like strings, lists, tuples, dictionaries, and more.
len(object)
object – A sequence (like string, list, tuple) or a collection (like dictionary, set, etc.).text = "Hello, World!"
print(len(text))
13
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
5
values = (10, 20, 30)
print(len(values))
3
person = {"name": "Alice", "age": 25, "city": "New York"}
print(len(person))
3
Note: len() returns the number of keys in the dictionary.
__len__() methodif len(my_list) == 0:len(5) → Raises TypeError because int has no lengthlen() is often used in interview coding problems to control loops, check constraints, or validate data. Know which data types it works on!
len() returns the number of items in an objectTypeError if used on unsupported types like int or floatAsk the user to enter a sentence. Print how many characters it contains:
sentence = input("Enter a sentence: ")
print("Number of characters:", len(sentence))
Connect what you noticed in the example with the idea below.
len() returns the number of items in a sized object. For strings, it counts Unicode code points, not encoded bytes.
len() of text always equals the number of UTF-8 bytes.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.