A list is a data structure that allows you to store multiple variables ins a single variable. Iteration is an essential part of programming. It allows you to efficiently loop through a list. Once the list has been created you can easily iterate through it. In this post, you will learn how to iterate through a List in Python.
Method to iterate through a List in Python
Let’s know all the methods that you can use to iterate through a list in python.
Method 1: Using a For Loop
The most common method to iterate through a list in Python is by using a loop. A for loop allows us to iterate through each item in the list. After that, you can take a specific operation on each item. Use the below lines of code to loop through the list.
my_list = [10, 20, 30, 40, 50] for item in my_list: print(item)
10 20 30 40 50
Method 2: Iterate through a List in Python Using the Range Function
Iterating through a list in Python can be achieve by using the range function. It allows you to create a series of numbers that can be used to access each element in the list. Run the below lines of code to implement this method.
my_list = [10, 20, 30, 40, 50] for i in range(len(my_list)): print(my_list[i])
10 20 30 40 50
Method 3: Using the Enumerate Function
Using the enumerate function in Python, you can loop through a list and also keep track of the index. Thus making it very useful in case you want to access both the index number and the item in the list.
Execute the below lines of code to use this method.
my_list = [10,20,30,40,50] for i, item in enumerate(my_list): print(i, item)
0 10 1 20 2 30 3 40 4 50
You now have three options to loop through a list in Python. The first is through a for loop, the second is the range function, and the last is enumerate function. You can select the technique that best suits your requirements to iterate through the list easily.