In Python, you can retrieve data one by one from a collection of various data by using a for statement. But sometimes you want to retrieve the index of that data as well as the data.
This time, I will explain how to get the index of data with the for statement and its application.
Table of contents [Hide] 1 [Get index with for statement using list](## Get index with for statement using list) 1.1 [Method using range](Method using ### range) 1.2 [Method using enumerate](Method using ### enumerate) 2 [Loop two lists in parallel](## Loop two lists in parallel) 2.1 [Use range](Use ### range) 2.2 [Use enumerate](### Use enumerate) 2.3 [Use zip function](Use ### zip function)
Of the for statements, especially for for statements that use lists and tuples, there are times when you want to use that index. Therefore, the Python for statement provides a way to retrieve the index of the retrieved element.
In Python for statement, it is common to use the range function to loop, but you can use that range to retrieve the index.
list = ['python', 'Hello', 'world']
for i in range(len(list)):
list_item = list[i]
print('{0}:{1}'.format(i, list_item))
Instead of retrieving data directly from the list, the len () function retrieves the length of the list and loops by that amount. Then, the value of variable 1 at that time becomes the index, so the index-th element is taken out in the for statement, stored in another variable, and finally output together.
You can also retrieve the index properly with this method. However, the code will be a little hard to read. Besides, it feels strange to not loop directly in the list even though the main thing is to extract the elements of the list.
list = ['python', 'Hello', 'world']
for i in range(len(list)):
list_item = list[i]
print('{0}:{1}'.format(i, list_item))
Execution result
0:python 1:Hello 2:world
I used range to retrieve the index earlier, but the code became very difficult to read. So Python provides a function to retrieve the index with clean code. That is enumerate.
for variable 1,Variable 2 in enumerate(list):
print('{0}:{1}'.format(Variable 1,Variable 2))
You can use the enumerate function to retrieve the element index and the element at the same time. The index is stored in variable 1 and the element is stored in variable 2. Compared to the method using range, the number of lines is smaller and it is cleaner, and the code is very easy to read. To retrieve the index, use the enumerate function if possible.
list = ['python', 'Hello', 'world']
for i, j in enumerate(list):
print('{0}:{1}'.format(i, j))
Execution result
0:python 1:Hello 2:world
You can use range to loop between two lists, just like a normal for statement.
for variable in rage(len(Listing 1)):
print('{0}, {1}'.format(Listing 1[variable],Listing 2[variable]))
The loop is rotated by the length of Listing 1 extracted by the len function. Then, since the value of'variable'at that time is equivalent to the index, you can loop the two lists by extracting the variable th element of each list.
list1 = ['python', 'Hello', 'world']
list2 = ['Python', 'programming', 'beginner']
for i in range(len(list1)):
print('list1:{0}, list2{1}'.format(list1[i], list2[i]))
Execution result
list1:python, list2Python list1:Hello, list2programming list1:world, list2beginner
I've been able to loop through the two lists and output both elements. However, with the method using range, the code is still difficult to read.
Next, the possible method is to use the enumerate mentioned earlier.
for variable 1,Variable 2 in enumerate(Listing 1):
print(‘{0}, {1}'.format(Variable 2,Listing 2[Variable 1]))
With the enumerate function, you can retrieve the index of the retrieved element. By using it, the elements in Listing 2 are extracted. The code is shorter and looks better than using range, but it's hard to see because it uses two variables separately, and it seems to be confusing.
list1 = ['python', 'Hello', 'world']
list2 = ['Python', 'programming', 'beginner']
for i,j in enumerate(list1):
print('list1:{0}, list2:{1}'.format(j, list2[i]))
Execution result
list1:python, list2:Python list1:Hello, list2:programming list1:world, list2:beginner
The method of looping between two lists using range and enumerate is not only hard to see, but also has another problem. It can cause an error if the two lists are of different lengths.
list1 = ['python', 'Hello', 'world', 'test']
list2 = ['Python', 'programming', 'beginner']
for i,j in enumerate(list1):
print('list1:{0}, list2:{1}'.format(j, list2[i]))
Execution result
print(‘list1:{0}, list2:{1}’.format(j, list2[i])) IndexError: list index out of range
In this example, list1 is 4 in length, so the loop is repeated 4 times. However, since list2 is 3 in length, this will result in an error because the element cannot be referenced the 4th time in the loop. In other words, when using range and enumerate, you have to consider the length of the list, which is a bit annoying.
To solve the problem of code readability and list length, it's a good idea to use the zip function when running the two loops.
for variable 1,Variable 2 in zip(Listing 1,Listing 2):
print('{0}, {1}'.format(Variable 1,Variable 2))
You can use the zip function to extract each element from two or more lists and store the elements in list 1 in variable 1 and the elements in list 2 in variable 2. The code is very clean and easy to see. Furthermore, if the list lengths are different, it will automatically adjust to the short list length, so you do not have to think about the list length one by one.
list1 = ['python', 'Hello', 'world', 'test']
list2 = ['Python', 'programming', 'beginner']
for i, j in zip(list1, list2):
print('{0}, {1}'.format(i,j))
Execution result
python, Python Hello, programming world, beginner
Reference site [Introduction to Python] How to get the index of data with a for statement
Recommended Posts