In this Python tutorial, we will discuss how Python loop through a list. Here we will illustrate various ways to iterate or loop through a Python list with examples.
We can loop through a list in Python using the 8 different methods. However, all 8 methods are listed below.
- Using for loop
- Using for loop and range()
- Using while loop
- Using list comprehension
- Using for loop with lambda
- Using for loop with enumerate()
- Using numpy library
- Using the iter & next functions
Python loop through a list
Here we will discuss all 8 methods to loop through a list in Python. And we will start with the first method of using for loop in Python.
Method 1: Python loop through a list using for loop
One of the basic ways to iterate or loop through a list is by using the for loop in Python.
An example of using for loop to loop through a list is given below.
# Defining a list
us_states = ['Alaska', 'Arizona', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia']
# Looping through each list element
for state in us_states:
print(state)
In the above example, we denied a list named us_states containing multiple USA state names.
After this, we just used the for loop to iterate over each list element and print it using the print() function.
The output of the above Python program is shown below.
Alaska
Arizona
California
Colorado
Connecticut
Delaware
Florida
Georgia
Read: Linked Lists in Python
Method 2: Python loop through a list using for loop and range()
Another way to loop through a list is by using for loop with the range() function.
Generally, the range() is a built-in function in Python that is used to generate a sequence of numbers.
Here is how we can use the for loop and range() to loop through a Python list.
# Defining a list
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia']
# Using for loop and range()
for i in range(len(cities)):
print(i+1 ,cities[i])
In the above example, we are using the for loop and range() function together to iterate over each list item. And, we will also print an index for each item.
Here is the result of the above Python program.
1 New York
2 Los Angeles
3 Chicago
4 Houston
5 Phoenix
6 Philadelphia
Read: Python concatenate list
Method 3: Python loop through a list using a while loop
Other than for loop, we can also use the while loop in Python to iterate or loop through a list.
Here is an example of this in Python.
# Defining a list
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia']
# Defining a counter
counter = 0
# Using while loop
while counter < len(cities):
print(cities[counter])
counter += 1
In the above python code:
- The cities list contains the names of six cities.
- A counter variable is initialized to 0.
- The while loop executes as long as the counter is less than the length of the cities list.
- Inside the loop, the current element of the cities list is printed using the counter as an index.
- The counter is incremented by 1 at the end of each iteration.
- Once the counter is equal to the length of the cities list, the loop exits.
Here is the result of the above Python program.
New York
Los Angeles
Chicago
Houston
Phoenix
Philadelphia
Read: How to Reverse a List in Python
Method 4: Python loop through a list using list comprehension
List comprehension is a quick walk to take a list, perform certain operations on all the list items, and form a new list from it.
However, instead of performing some operation, we can just use the print() function in the list comprehension. And this will result in just looping over the given list.
Here is an example of this in Python.
# Defining a list
us_states = ['Alaska', 'Arizona', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia']
# Using list comprehension to loop over list and print value
[print(state) for state in us_states]
Once we execute the above Python program, we will get the following result.
Alaska
Arizona
California
Colorado
Connecticut
Delaware
Florida
Georgia
Read: Python Extend Vs Append
Method 5: Python loop through a list using for loop with lambda function
Another method to iterate over the list in Python is by using the for loop with the lambda function.
The lambda function in Python is a function that we can execute in just one line of code. Moreover, we generally use the lambda function to perform certain operation on the list item.
Here is an example of this in Python.
# Defining a list
nums = [21, 23, 26, 54, 65]
# Defining another list
square_nums = []
# Defining lambda
func = lambda x: x*x
# Using lambda and for loop
for x in nums:
square_nums.append(func(x))
# Iterating over new list
for y in square_nums:
print(y)
In the above example, we have defined a list of numbers and then we defined another empty list.
After this, we defined a lambda function and then we are using the for loop to iterate over the list item and perform the lambda function on it.
In the last, we are appending the new value to the list. And once we iterate over the new list, we will get the following result.
441
529
676
2916
4225
Read: How to find a string from a list in Python
Method 6: Python loop through a list using for loop with enumerate()
The enumerate() is a built-in Python function that allows iteration over a sequence while keeping track of the index of the current item. It returns an iterator that yields pairs consisting of the index and the item at that index.
Here is an example of this task in Python.
# Defining a list
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia']
# Using for loop and enumerate()
for index, city in enumerate(cities) :
print(index ,city)
The result of the above Python program is shown below.
0 New York
1 Los Angeles
2 Chicago
3 Houston
4 Phoenix
5 Philadelphia
Read: How to add string to list Python
Method 7: Python loop through a list using the numpy library
NumPy is a popular Python library utilized for scientific calculation in Python.
In this method, we will create a numpy array using the list in Python and then we will iterate over the array elements using the for loop.
Here is an example of this in Python.
# Importing numpy
import numpy as np
# Defining a list
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia']
city_array = np.array([city for city in cities])
# Looping over an array
for name in np.nditer(city_array):
print(name)
After executing the above Python program, we will get the following result.
New York
Los Angeles
Chicago
Houston
Phoenix
Philadelphia
Read:
Method 8: Python loop through a list using the iter & next functions
For creating and iterating over an iterator object in Python, the built-in iter() and next() functions are utilized. It is common to use iterators to represent streams of data since they may be iterated (looped) upon.
Now, we can use both of these functions to loop through a list in Python
Here is an example of this task in Python.
# Defining a list
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia']
# Creating an iterator
city_iterator = iter(cities)
# Uisng while loop
while True:
try:
# Using next() to iterate over list items
city = next(city_iterator)
print(city)
except StopIteration:
break
- In the above code, first, we defined a list named cities and created an iterable object using the iter() function.
- Then we used the while loop and within the while loop, we utilized the next() function to iterate over each value given in the iterable.
The result of the above Python program is given below.
You may also like to read the following Python tutorials.
- How to insert item at end of Python list
- How to get string values from list in Python
- How to get unique values from a list in Python
Conclusion
So, in this Python tutorial, we have discussed How Python loop through a list works. Moreover, we have covered 8 different examples of how to loop through a list in Python.
Here is the list of 8 methods that we have covered.
- Using for loop
- Using for loop and range()
- Using while loop
- Using list comprehension
- Using for loop with lambda
- Using for loop with enumerate()
- Using numpy library
- Using the iter & next functions
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.