How does the len() function relate to index values for lists?


#1

Question

What is the relationship between the value returned by len() and the indexes which can be used to access elements of a list?

Answer

The len() function returns the number of items in a list. Since list indexes start at 0, the value of len() represents a value one larger than the last index. This means the valid indexes of a list are any number between 0 and len() - 1. The len() function is commonly used with the range() function. Since range() by default, returns a list from 0 to one less than the number passed, the len() of a list can be passed to range() to generate a valid list of indexes. This is shown in the example below.

examples = ['red', 'green', 'blue', 'orange']

# This will print 4 which is the number of elements in examples.
print(len(examples))

# This will return a list ([0, 1, 2, 3]) which provides indexes to the examples.
for color in range(len(examples)):
   print(examples[color])