Open In App

Python | Iterate over multiple lists simultaneously

Last Updated : 06 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 of iteration of multiple lists, we are iterating over 3 lists at a time. We can iterate over lists simultaneously in ways:

  1. zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists. Below is an implementation of the zip function and itertools.izip which iterates over 3 lists: 

Python3




# Python program to iterate
# over 3 lists using zip function
 
import itertools
 
num = [1, 2, 3]
color = ['red', 'while', 'black']
value = [255, 256]
 
# iterates over 3 lists and executes
# 2 times as len(value)= 2 which is the
# minimum among all the three
for (a, b, c) in zip(num, color, value):
     print (a, b, c)


Output:

1 red 255
2 while 256
  1. itertools.zip_longest() : zip_longest stops when all lists are exhausted. When the shorter iterator(s) are exhausted, zip_longest yields a tuple with None value. Below is an implementation of the itertools.zip_longest which iterates over 3 lists: 

Python3




# Python program to iterate
# over 3 lists using itertools.zip_longest
 
import itertools
 
num = [1, 2, 3]
color = ['red', 'while', 'black']
value = [255, 256]
 
# iterates over 3 lists and till all are exhausted
for (a, b, c) in itertools.zip_longest(num, color, value):
    print (a, b, c)


Output:

1 red 255
2 while 256
3 black None
  1. Output:
1 red 255
2 while 256
3 black None

We can also specify a default value instead of None in zip_longest() 

Python3




# Python program to iterate
# over 3 lists using itertools.zip_longest
 
import itertools
 
num = [1, 2, 3]
color = ['red', 'while', 'black']
value = [255, 256]
 
# Specifying default value as -1
for (a, b, c) in itertools.zip_longest(num, color, value, fillvalue=-1):
    print (a, b, c)


Output:

1 red 255
2 while 256
3 black -1

Time complexity: O(n), where n is the length of the longest list

Auxiliary space: O(1)

Note : Python 2.x had two extra functions izip() and izip_longest(). In Python 2.x, zip() and zip_longest() used to return list, and izip() and izip_longest() used to return iterator. In Python 3.x, there izip() and izip_longest() are not there as zip() and zip_longest() return iterator.

Another approach to iterate over multiple lists simultaneously is to use the enumerate() function. The enumerate() function allows you to iterate over a list and keep track of the current index of each element. You can use this index to access the corresponding elements in the other lists.

For example:

Python3




list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']
 
for i, element in enumerate(list1):
    print(element, list2[i], list3[i])


Output

1 a x
2 b y
3 c z

Time complexity: O(n), where n is the length of the longest list (in this case, n=3).
Auxiliary space: O(1), as no extra space is being used.

#Example-4:

Approach:

In this approach, the zip() function takes three generator expressions as arguments. Each generator expression yields the elements of each iterable on-the-fly, without creating a list or tuple to store the values.

Python3




for item1, item2, item3 in zip((1, 2, 3), ('a', 'b', 'c'), (True, False, True)):
    print(item1, item2, item3)


Output

1 a True
2 b False
3 c True

The time and space complexity of this code is constant time (O(1)) and constant space (O(1)).

The reason is that the code only iterates over three tuples with three elements each, and the number of iterations is fixed and does not depend on the input size. Therefore, the time complexity is constant.

Similarly, the space complexity is also constant, as the code only creates three tuples with three elements each, and the number of tuples created is also fixed and does not depend on the input size. Therefore, the space complexity is also constant.



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
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 = "geeksforgeeks" # 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
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print(dictionary_name[index][i] Example: Python Code #
2 min read
Article Tags :
Practice Tags :