We might ask why we need to iterate a list in Python with indexes if we already saw in the example of iterate a list in Python how easy it is to iterate a list of elements in Python using a for-each loop. In that case, each iteration of the loop left us the iterated element in a variable, making its manipulation much easier.
The truth is that iterating a list in Python would be the simple case. But if you come from languages other than Python you may be thinking about how to access the list through its indexes, that is, through the value of the index that the element has. Thus, in this example, we are going to see how to iterate a list in Python with indexes.
Declare a list of elements in Python
The first step to iterate a list in Python with indexes will declare the list of elements:
list = ["carmen","elena","lucia","sara","patricia","sonsoles"]
We see that all the elements are enclosed in square brackets and separated by commas.
In this case we have created a list with women’s names.
Using ranges to loop through a list
Now we are going to use the for loop. What happens is that in Python the loop is itself represented by a for-each loop. So if we want to iterate through indexes, the loop must go through a list of numbers.
This list of numbers will go from 0, which is the initial index value, to the length of the list. So the first thing we need to know is that the length of the list is calculated using the function
len()
.
size = len(list)
The next thing will be to create a range of numbers that we will go through and that will be the indexes. In this case we are going to use the
range()
to be able to create that list. The range will be from 0 to the size of the string.
range(0,len(list))
To access the element using the index, we need to enclose the index in square brackets. This way we could access the elements individually by writing.
list[0] #first item list[1] #second element ...
Using for-each to iterate a list in Python with indexes
So, the most relevant part of our Python code, to be able to iterate a list in Python with indexes, will be the one that allows us to use this range with the for-each loop and access through indexes as follows.
print "Scroll list by Indices"
for x in range(0,len(list)):
print list[x]
In this way we will have already managed to iterate a list in Python with indexes and display its contents on the console using the function
print()
