Access List Index in for Loop in Python (2 Examples)

 

In this article, I’ll demonstrate how to access a list index in a for loop in Python.

The tutorial contains these contents:

Let’s dive right in!

 

Exemplifying Data

The following data, which is a list of integers, is used as a basis for this Python tutorial.

some_list = [1, 3, 5, 7, 9, 11, 13, 15]          # creating sample list

 

Example 1: Pairing Indices & Elements of Lists Using enumerate() Function

In this example, we will use the enumerate() function, which takes a list as input and returns a list of tuples. Each tuple is an index/element pair, as given below.

enum_list = enumerate(some_list)                 # enumerating the list
for index, elem in enum_list:
    print(index, elem, sep=': ')                 # printing the index-element pairs
 
# 0: 1
# 1: 3
# 2: 5
# 3: 7
# 4: 9
# 5: 11
# 6: 13
# 7: 15

 

Example 2: Pairing Indices & Elements of Lists Using range() Function

Another way of pairing indices and elements of lists is simply using the index number to get the indices and elements, which can be seen below.

for index in range(len(some_list)):
    print(index, some_list[index], sep=': ')    # printing the index-element pairs
# 0: 1
# 1: 3
# 2: 5
# 3: 7
# 4: 9
# 5: 11
# 6: 13
# 7: 15

 

Video, Further Resources & Summary

I have recently published a video on my YouTube channel, which demonstrates the Python programming codes of this article. You can find the video below:

 

The YouTube video will be added soon.

 

Furthermore, you might want to have a look at the related tutorials on my website. You can find a selection of articles about related topics such as lists, data elements, loops, and data conversion below:

 

You have learned on this page how to get index and element pairs of a list in a for loop in Python programming. If you have further comments or questions, don’t hesitate to let me know in the comments below. Furthermore, please subscribe to my email newsletter to get regular updates on new articles.

 

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top