The len() Function
The len() function returns the number of items in its argument as an integer.
Why Collection Size Matters
Programs often need to know how many items they are working with. The len() function returns the number of items in its argument as an integer. That count can describe the characters in a string, the elements in a list, or the items in another collection. It also helps a program determine which positions are available when it needs to traverse a list.
What do you think happens?
What does len('Hello world') return? Count every character, including the space.
Reveal answer
11
The string contains five letters in Hello, one space, and five letters in world. len() counts every character, including spaces.
Mapping Length to Positions
A collection's length and its valid indices are connected. Because indices start at 0, the final valid index is one less than the collection's length. Therefore, if a list has length 4, its valid indices are 0, 1, 2, and 3. The expression range(len(my_list)) produces exactly those index values, making it useful when a loop must access positions in the list.
my_list = [12, 18, 25]
for i in range(len(my_list)):
print(i, my_list[i])- 1The list has three elements, so
len(my_list)is 3. - 2The loop receives index 0 and reads
my_list[0], which is 12. - 3The loop receives index 1 and reads
my_list[1], which is 18. - 4The loop receives index 2 and reads
my_list[2], which is 25.
len(my_list)returns 3.range(3)supplies the indices 0, 1, and 2.my_list[i] reads the element at the current index.
0 12
1 18
2 25Reading Without Changing
A simple for loop traverses a list by assigning each element's value to the loop variable. This is the natural pattern when the task is to inspect or display values. The loop does not provide a list position for the current value, so this pattern is intended for reading rather than updating list elements.
Mina
Omar
TariqUpdating Through Indices
To update list elements in place, the loop needs the position of each element. The pattern for i in range(len(list)) supplies those positions. At each iteration, list[i] can be read and assigned a new value. The list changes at the position represented by the current index.
numbers = [2, 4, 6]
for i in range(len(numbers)):
numbers[i] = numbers[i] + 1
print(numbers)- 1Before the loop, numbers is [2, 4, 6].
- 2At i = 0, numbers[0] changes from 2 to 3. The list becomes [3, 4, 6].
- 3At i = 1, numbers[1] changes from 4 to 5. The list becomes [3, 5, 6].
- 4At i = 2, numbers[2] changes from 6 to 7. The list becomes [3, 5, 7].
- The list has length 3, so the indices are 0, 1, and 2.
- numbers[i] identifies the element at the current position.
- Each assignment replaces the current element with a value one greater.
[3, 5, 7]Tracing an Index-Based Update
Determine the final list after this loop: scores = [10, 20, 30]; for i in range(len(scores)): scores[i] = scores[i] - 5.
- 1Find the length
scores has three items, so
len(scores)is 3 andrange(len(scores))supplies indices 0, 1, and 2. - 2Process index 0
scores[0] changes from 10 to 5. The list is [5, 20, 30].
- 3Process index 1
scores[1] changes from 20 to 15. The list is [5, 15, 30].
- 4Process index 2
scores[2] changes from 30 to 25. The list is [5, 15, 25].
The final list is [5, 15, 25].
Counting Different Collections
len() works on collection types, but the meaning of an item depends on the type. For a string, an item is a character, so letters, digits, spaces, and punctuation are all counted. For a list, an item is an element. len() can also operate on tuples, dictionaries, and sets; the source material emphasizes the general principle that it returns the number of items in the collection.
3
2
3Mistakes with Length and Indices
Common mistake Treating the length as the final valid index.
What it looks likeA list with length 3 has indices 0, 1, and 2, not 0, 1, 2, and 3.
Why it failsIndices start at 0, so the final valid index is one less than the length.
Do this insteadUse range(len(my_list)) to generate the valid positions.
Common mistake Using a simple for loop when the list must be updated.
What it looks likefor value in numbers: value = value + 1Why it failsThe loop variable receives an element's value, but the pattern does not provide the list position needed to assign back to the original list.
Do this insteadUse for i in range(len(numbers)) and assign through numbers[i].
Common mistake Forgetting spaces or punctuation when counting a string.
What it looks likeExpecting len("Hello world") to count only the letters.
Why it failslen()counts every character, including the space.Do this insteadCount letters, spaces, digits, and punctuation as individual characters.
Practice with len()
For each task, choose the appropriate traversal pattern and predict the result before running the code. First, display every item in items without changing the list. Next, increase every number in values by 2 using an index-based loop. Finally, determine the length of the string "A B!" and identify its valid indices.
Hints
- Use a simple for loop when the task only reads or displays values.
- Use
range(len(values))when the task updates values in the original list. - Count the space and exclamation mark in the string.
To check your reasoning, trace the index-based loop one iteration at a time. Write the current index, the element at that index before the assignment, and the complete list after the assignment. This makes the mutation visible instead of treating the loop as one unexplained operation.
Key Takeaways
- 1
len()returns the number of items in its argument as an integer. - 2For strings,
len()counts every character, including spaces and punctuation. - 3A simple for loop reads each element directly and is suitable for inspection or display.
- 4The pattern for i in
range(len(list))generates valid indices for reading or updating list elements. - 5If a collection has length n, its highest valid index is n - 1.
At a glance
len()determines the number of items in a collection.- String length includes letters, spaces, punctuation, and other characters.
- Simple for loops are designed for reading values directly.
range(len(list))supplies the valid positions needed to update list elements.- Tracing each index and intermediate list state helps prevent off-by-one errors and predict mutations.