Python - Iterate over indices of a list using range()
Iterate over indices of a list using range() in Python
To iterate over indices of a list using range() in Python, define a range with the length of the list as stop value, and use this range object as an iterator in the For loop.
Length of the list returns the number of elements in the list. Say that length is n. Now, if we define a range with this length n as stop value as shown in the following, it would generate a sequence of values from 0 to n-1 which are our required indices of the elements in the list.
range(n)
The syntax to iterate over the indices of a list my_list using For loop and range() function is
for i in range(len(my_list)):
// your code
Now, let us go through some examples.
1. Iterate over indices of a list using range()
In the following program, we take a list my_list with some string values, and iterate over the indices of this list using For loop and range()
.
Python Program
my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
print(i)
Output
0
1
2
2. Iterate over indices of list using range() and access the list elements
In the following program, we access the elements of the list using the index in the For loop.
Python Program
my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
print(my_list[i])
Output
apple
banana
cherry
Summary
In this tutorial of Python Ranges, we learned how to iterate over the indices of a list using range() function, with the help of examples.