Open In App

Iterate over a list in Python

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size.

In Python, the list is a type of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets, lists in Python are ordered and have a definite count. In this article, we will see how to iterate over a list in Python and also Python loop through list of strings.

Python Iterate Over a List

Let’s see all the different ways to iterate over a list in Python and the performance comparison between them.

Iterate over a list using For loop

We can iterate over a list in Python by using a simple For loop.

Python
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
 
# Using for loop
for i in list:
    print(i)

Output
1
3
5
7
9

Time complexity: O(n) – where n is the number of elements in the list.
Auxiliary space: O(1) – as we are not using any additional space.

Iterate through a list using for loop and range()

In case we want to use the traditional for loop which iterates from number x to number y.  

Python
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
 
# getting length of list
length = len(list)
 
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
    print(list[i])

Output
1
3
5
7
9

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), which is constant space

Iterate through a List in Python using a while loop 

We can also iterate over a Python list using a while loop.

Python
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
 
# Getting length of list
i = 0
 
# Iterating using while loop
while i < len(list):
    print(list[i])
    i += 1

Output
1
3
5
7
9

Time complexity: O(n) where n is the length of the list.
Auxiliary space: O(1) as only a constant amount of extra space is used for variables i and length.

Iterate through a list using list comprehension 

We can use list comprehension(possibly the most concrete way) to iterate over a list in Python.  

Python
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
 
# Using list comprehension
[print(i) for i in list]

Output
1
3
5
7
9

Iterate through a List in Python using enumerate()

If we want to convert the list into an iterable list of tuples (or get the index based on a condition check, for example in linear search, you might need to save the index of minimum element), you can use the enumerate() function

Python
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
 
# Using enumerate() 
for i, val in enumerate(list):
    print (i, ",",val)

Output
0 , 1
1 , 3
2 , 5
3 , 7
4 , 9

Note: Even method 2 can be used to find the index, but method 1 can’t (Unless an extra variable is incremented every iteration) and method 5 gives a concise representation of this indexing. 

Iterate through a List in Python using the iter function and the next function 

Here is an additional approach using the iter function and the next function:

Python
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]

# Create an iterator object using the iter function
iterator = iter(list)

# Use the next function to retrieve the elements of the iterator
try:
    while True:
        element = next(iterator)
        print(element)
except StopIteration:
    pass

Output
1
3
5
7
9

Time complexity: O(n)
Auxiliary space: O(1)

Iterate over a list in Python using the map() function

Use the map() function to apply a function to each element of a list.

Python
# Define a function to print each element
def print_element(element):
    print(element)

# Create a list
my_list = [1, 3, 5, 7, 9]

# Use map() to apply the print_element() function to each element of the list
result = map(print_element, my_list)

# Since map() returns an iterator, we need to consume
# the iterator in order to see the output
for _ in result:
    pass

Output
1
3
5
7
9

Time complexity: O(n), where n is the length of the list. 
Auxiliary space: O(1)

Python Iterate Over Multiple Lists Using zip() Function

In this example, the zip() function is utilized to concurrently iterate over elements from two lists, list1 and list2, pairing corresponding elements together in tuples for subsequent printing.

Python
list1 = [1, 2, 3]
list2 = ['p', 'q', 'r']

# Using zip() to iterate over multiple lists simultaneously
for i1, i2 in zip(list1, list2):
    print(f'{i1} -> {i2}')

Output
1 -> p
2 -> q
3 -> r

Iterate over a list in Python Using NumPy

For very large n-dimensional lists (for example an image array), it is sometimes better to use an external library such as numpy. We can use np. enumerate() to mimic the behavior of enumerating. The extra power of NumPy comes from the fact that we can even control the way to visit the elements (Fortran order rather than C order, say :)) but the one caveat is that the np.nditer treats the array as read-only by default, so one must pass extra flags such as op_flags=[‘readwrite’] for it to be able to modify elements.

Python
import numpy as geek

# creating an array using
# arrange method
a = geek.arange(9)

# shape array with 3 rows
# and 4 columns
a = a.reshape(3, 3)

# iterating an array
for x in geek.nditer(a):
    print(x)

Output: 

0
1
2
3
4
5
6
7
8

Time complexity: O(n)
Auxiliary space: O(1)

Iterate over a list in Python – FAQs

How does Python iterate over a list?

Python iterates over a list using a for loop. Each element in the list is accessed sequentially. Here’s a basic example:

my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)

In this example, item takes the value of each element in my_list one at a time, and the print function outputs each value.

What are the methods for iterating over a list?

There are several methods to iterate over a list in Python:

For Loop: The most common way to iterate over a list.

for item in my_list:
print(item)

While Loop: Uses an index to iterate over the list.

i = 0
while i < len(my_list):
print(my_list[i])
i += 1

List Comprehension: A concise way to create a new list by iterating over an existing one.

new_list = [item * 2 for item in my_list]

Enumerate: Provides both index and value during iteration.

for index, item in enumerate(my_list):
print(index, item)

Map Function: Applies a function to all items in the list.

def square(x):
return x * x
squared_list = list(map(square, my_list))

What is traversing a list?

Traversing a list means accessing and processing each element of the list one by one. This is typically done to perform some operation on each element, such as printing values, modifying them, or applying a function.

How to iterate a list of lists?

To iterate over a list of lists, you can use nested for loops. Here’s an example:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for sublist in list_of_lists:
for item in sublist:
print(item)

In this example, sublist takes each list within list_of_lists, and then the inner loop iterates over each item in sublist.

How to iterate through a list function in Python?

If you want to use a function to iterate through a list, you can define a function that includes the iteration logic. Here’s an example:

def iterate_and_print(my_list):
for item in my_list:
print(item)
# Example usage
my_list = [1, 2, 3, 4, 5]
iterate_and_print(my_list)

In this function, iterate_and_print, the for loop iterates through my_list and prints each item.



Previous Article
Next Article

Similar Reads

Iterate Over a List of Lists in Python
Iterating over a list of lists is a common task in Python, especially when dealing with datasets or matrices. In this article, we will explore various methods and techniques for efficiently iterating over nested lists, covering both basic and advanced Python concepts. In this article, we will see how we can iterate over a list of lists in Python. I
3 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Iterate over characters of a string in Python
In Python, while operating with String, one can do multiple operations on it. Let's see how to iterate over the characters of a string in Python. Example #1: Using simple iteration and range() C/C++ Code # Python program to iterate over characters of a string # Code #1 string_name = &amp;quot;geeksforgeeks&amp;quot; # Iterate over the string for el
3 min read
Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 min read
Python - How to Iterate over nested dictionary ?
In this article, we will discuss how to iterate over a nested dictionary in Python. Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. Nested dictionary in use: {'Student 1': {'Name': 'Bobby', 'Id': 1, 'Age': 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, 'Age':
3 min read
Practice Tags :