Concepts / The len() Function

The len() Function

List traversal comes in two main forms: simple for loops for reading elements, and index-based loops using range(len()) for updating elements.

  • Programming

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.

  • 10
  • 11
  • 12
Reveal answer

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.

len = 3producesproducesproducesmy_list[12, 18, 25]012118range(3)range(len(my_list))225
Which index points to each list element, and how does range(len(my_list)) generate exactly those valid positions?

my_list = [12, 18, 25] for i in range(len(my_list)): print(i, my_list[i])

Reading 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.

gives valuegives positionfor value in listreads each valuevalueinspect or displayfor i inrange(len(list))uses each positionlist[i]read or modify
How does a simple for loop read values directly, while an index-based loop uses positions to modify the original list?
python
Output
Mina
Omar
Tariq

Updating 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.

update index 0update index 1update index 2[2, 4, 6]before the loopi = 0[3, 4, 6]i = 1[3, 5, 6]i = 2[3, 5, 7]
What is the list after each loop iteration, and which element changes when the current index is used?

numbers = [2, 4, 6] for i in range(len(numbers)): numbers[i] = numbers[i] + 1 print(numbers)

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.

Find the length: scores has three items, so len(scores) is 3 and range(len(scores)) supplies indices 0, 1, and 2.

Process index 0: scores[0] changes from 10 to 5. The list is [5, 20, 30].

Process index 1: scores[1] changes from 20 to 15. The list is [5, 15, 30].

Process 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.

counts characterscounts elementscounts items"Hi!"3 characterslen()returns an integer["red", "blue"]2 elements(4, 8, 12)3 items
What exactly is being counted when len() is applied to a string, list, or other collection?
python
Output
3
2
3

Mistakes with Length and Indices

  • Treating the length as the final valid index.

    Indices start at 0, so the final valid index is one less than the length.

    Fix: Use range(len(my_list)) to generate the valid positions.

  • Using a simple for loop when the list must be updated.

    The loop variable receives an element's value, but the pattern does not provide the list position needed to assign back to the original list.

    Fix: Use for i in range(len(numbers)) and assign through numbers[i].

  • Forgetting spaces or punctuation when counting a string.

    len() counts every character, including the space.

    Fix: Count letters, spaces, digits, and punctuation as individual characters.

Practice with len()

MEDIUM

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.
  2. For strings, len() counts every character, including spaces and punctuation.
  3. A simple for loop reads each element directly and is suitable for inspection or display.
  4. The pattern for i in range(len(list)) generates valid indices for reading or updating list elements.
  5. If a collection has length n, its highest valid index is n - 1.

Key Takeaways

  • 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.