Loop Over List with Index in Python (2 Examples)
In this tutorial, you’ll learn how to loop over a Python list while accessing the index of each element in the list. We’ll explore multiple examples to accomplish this task.
The table of contents is structured as follows:
Let’s dive into it!
Data Initialization
Let’s start by initializing a simple list with strings:
my_list = ['apple', 'banana', 'orange', 'grape']
Example 1: Iterate Over List with Index Using enumerate() Function
The first example involves using the built-in enumerate() function in Python. Here’s how it works:
for index, element in enumerate(my_list): print(f"Index: {index}, Element: {element}") # Index: 0, Element: apple # Index: 1, Element: banana # Index: 2, Element: orange # Index: 3, Element: grape
In this example, the enumerate()
function returns both the index and element at each iteration, as shown above.
Example 2: Iterate Over List with Index Using range() Function
The second example involves using the range() function to generate the indices of the list. Here’s an example:
for index in range(len(my_list)): element = my_list[index] print(f"Index: {index}, Element: {element}") # Index: 0, Element: apple # Index: 1, Element: banana # Index: 2, Element: orange # Index: 3, Element: grape
In this example, we use the range()
function to generate a sequence of indices from 0 to the length of the list. We then access the corresponding element using the index and print the index and element.
Video, Further Resources & Summary
Do you need more explanations on looping over a list with an index in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
The YouTube video will be added soon.
Furthermore, you could have a look at some of the other tutorials on Statistics Globe:
- Introduction to List in Python
- Convert List from Character String to Integer in Python
- Check If Key Exists in List of Dictionaries in Python
- Access Dictionary within List in Python
This post has shown how to loop over a list with an index in Python. In case you have further questions, you may leave a comment below.
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.
Statistics Globe Newsletter