[Introduction to Python] How to get the index of data with a for statement

[Introduction to Python] How to get the index of data with a for statement

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)

Get an index with a for statement using a list

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.

Method using range

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

Method using enumerate

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

use range

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.

use enumerate

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

Use zip function

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

[Introduction to Python] How to get the index of data with a for statement
[Introduction to Python] How to get data with the listdir function
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
How to get a list of files in the same directory with python
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] What is the method of repeating with the continue statement?
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
How to get the number of digits in Python
[Introduction to Python] How to iterate with the range function?
Python script to get a list of input examples for the AtCoder contest
How to get the Python version
How to get started with Python
How to define multiple variables in a python for statement
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
I didn't know how to use the [python] for statement
How to get into the python development environment with Vagrant
Turn an array of strings with a for statement (Python3)
Get the source of the page to load infinitely with python.
[Python] I want to use only index when looping a list with a for statement
How to identify the element with the smallest number of characters in a Python list?
How to determine the existence of a selenium element in Python
How to change the log level of Azure SDK for Python
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
python / pandas / dataframe / How to get the simplest row / column / index / column
How to get the ID of Type2Tag NXP NTAG213 with nfcpy
Get the value of a specific key up to the specified index in the dictionary list in Python
How to check the memory size of a variable in Python
[Python] How to get the first and last days of the month
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
How to get a stacktrace in python
After hitting the Qiita API with Python to get a list of articles for beginners, we will visit the god articles
How to get the vertex coordinates of a feature in ArcPy
[Python] How to get a value with a key other than value with Enum
How to use "deque" for Python data
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
[Introduction to Data Scientists] Basics of Python ♬
How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)
PhytoMine-I tried to get the genetic information of plants with Python
[Django Learned with the Devil's Blade] How to get a query set for forward / reverse reference
python memo: enumerate () -get index and element of list at the same time and turn for statement
Get the number of searches with a regular expression. SeleniumBasic VBA Python
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to judge authenticity with if statement (True and None)
How to get the date and time difference in seconds with python
Try to image the elevation data of the Geographical Survey Institute with Python
I tried to get the authentication code of Qiita API with Python.
I tried to get the movie information of TMDb API with Python
How to access data with object ['key'] for your own Python class
Get the key for the second layer migration of JSON data in python
How to calculate the volatility of a brand
How to read a CSV file with Python 2/3
[Python] Get the files in a folder with Python
Get a ticket for a theme park with python
Get the caller of a function in Python
I tried to get CloudWatch data with Python
[Introduction to Python] How to handle JSON format data
How to specify attributes with Mock of python
How to write a ShellScript Bash for statement
[Introduction to Udemy Python3 + Application] 43. for else statement