What is range(len()) in Python
In Python, len() function with an iterable as argument returns the number of elements in that iterable. And range(len()) returns a generator with a sequence of integers from 0 upto the length of the iterable.
This sequence of integers returned by the range() function can be used as indices of the elements in the iterable.
For example, consider the following list.
my_list = ['apple', 'banana', 'cherry']
len(my_list) returns a value 3, because there are three elements in the list. Easy.
Now, we pass the value returned by the len() function as argument to the range() function.
This creates a range object with a start value of 0 and stop value of 3, where 3 is the length of the given list. And the sequence of these integer values in the range object is given below.
0 1 2
If we can use a For loop to iterate over the range, we have access to the index of the element in the For loop, as shown in the following program.
Run Code Copy
my_list = ['apple', 'banana', 'cherry'] for i in range(len(my_list)): print(my_list[i])
apple banana cherry
The same explanation holds for any ordered iterable, say tuple, string, etc.
In this tutorial of Python Ranges, we learned what range(len()) means, and how to use this expression to iterate over the indices of a given iterable.