The Wayback Machine - https://web.archive.org/web/20240818084658/https://www.geeksforgeeks.org/python-iterate-multiple-lists-simultaneously/
Open In App

Python | Iterate over multiple lists simultaneously

Last Updated : 06 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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
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
How to Iterate over months between two dates in Python?
In this article, we will discuss how to iterate over months between two dates using Python. We can iterate over months between two dates using timedelta and rrule methods. Method 1: Iteration using timedeltatimedelta() is used for calculating differences in dates and also can be used for date manipulations in Python Example: But using timedelta we
2 min read
Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
Iterate over a list in Python
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 P
8 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. Dictionary in Python is a collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair in Python. To Iterate through values in a dictionary you can use built-in m
7 min read
How to iterate over rows in Pandas Dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Let’s see the how to iterate over rows in Pandas Dataframe using iterrows() and itertuples() :Method #1: Using the DataFrame.iterrows() m
2 min read
How to Iterate over rows and columns in PySpark dataframe
In this article, we will discuss how to iterate rows and columns in PySpark dataframe. Create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf
6 min read
Different ways to iterate over rows in Pandas Dataframe
In this article, we will cover how to iterate over rows in a DataFrame in Pandas. Example # Defining a function to applydef print_row(row): print(f"Name: {row['Name']}, Age: {row['Age']}")# Iterating over rows using apply()df.apply(print_row, axis=1)[embed]https://www.youtube.com/watch?v=mT-2AxZLtvw&t=179s[/embed] Pandas Loop through RowsPandas
3 min read
Python | Ways to iterate tuple list of lists
List is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.Given a tuple list of lists, write a Python program to iterate through it and get all elements. Method #1: Use itertools.ziplongest C
5 min read
Python - Iterate through list without using the increment variable
Python Lists is much like flexible size arrays, declared in other languages like vector in C++, array list in Java, etc. Lists are heterogeneous, making it the most effective feature in Python. Lists are mutable, and hence can be modified even after they have been formed. The most common approach is to iterate through a list using the increment var
2 min read
How to iterate through a nested List in Python?
In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List. Iterating through a Nested List Lets us see how a typical nested list
2 min read
How to iterate through Excel rows in Python?
In this article, we are going to discuss how to iterate through Excel Rows in Python. In order to perform this task, we will be using the Openpyxl module in python. Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows a Python program to read and modify Excel files. We wil
2 min read
How we can iterate through list of tuples in Python
In this article, we will discuss different ways to iterate the list of tuples in Python. It can be done in these ways: Using Loop.Using enumerate().Method 1: Using Loop Here we are going to form a list of tuples using for loop. C/C++ Code # create a list of tuples with student # details name = [('sravan',7058,98.45), ('ojaswi',7059,90.67), ('bobby'
2 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game Development'}, {'Java': 'App Development', 'Kotli
3 min read
How to iterate through images in a folder Python?
In this article, we will learn how to iterate through images in a folder in Python. Method 1: Using os.listdirExample 1: Iterating through .png onlyAt first we imported the os module to interact with the operating system.Then we import listdir() function from os to get access to the folders given in quotes.Then with the help of os.listdir() functio
2 min read
Use For Loop to Iterate Tuple in Python
In this article, we will explore how to use a for loop to iterate through tuples in Python, along with some practical examples to illustrate its utility. Use For Loop to Iterate Tuple in PythonBelow are the ways by which we can use for loop to iterate Tuple in Python: Using Simple for loopTuple of TupleNested TuplesUsing enumerate functionsLoop thr
3 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
How to create a PySpark dataframe from multiple lists ?
In this article, we will discuss how to create Pyspark dataframe from multiple lists. ApproachCreate data from multiple lists and give column names in another list. So, to do our task we will use the zip method. zip(list1,list2,., list n) Pass this zipped data to spark.createDataFrame() method dataframe = spark.createDataFrame(data, columns) Exampl
2 min read
Integrate a Hermite_e series Over Axis 0 using Numpy in Python
In this article, we will cover how to integrate a Hermite_e series over axis 0 using NumPy in Python. NumPy e.hermeint() method We use the hermite e.hermeint() function present in the NumPy module of python to integrate a Hermite e series. The first parameter 'arr' is an array of coefficients from the Hermite e series. If 'arr' is multi-dimensional
3 min read
Benefit of NumPy arrays over Python arrays
The need for NumPy arises when we are working with multi-dimensional arrays. The traditional array module does not support multi-dimensional arrays. Let's first try to create a single-dimensional array (i.e one row & multiple columns) in Python without installing NumPy Package to get a more clear picture. C/C++ Code from array import * arr = ar
1 min read
Why is iterating over a dictionary slow in Python?
In this article, we are going to discuss why is iterating over a dict so slow in Python? Before coming to any conclusion lets have a look at the performance difference between NumPy arrays and dictionaries in python: Python Code # import modules import numpy as np import sys # compute numpy performance def np_performance(): array = np.empty(1000000
3 min read
Return the cumulative product of array elements over axis 0 treating NaNs as one in Python
In this article, we will discuss how to find the result of the power to which the negative input value is raised with Python and NumPy. ExampleInput: [[10. nan][nan 20.]] Output: [ 10. 10. 10. 200.] Explanation: The cumulative product of array elements over a given axis.NumPy.nancumprod method The numpy nancumprod() is used to return the cumulative
3 min read
Evaluate a Hermite series at points x broadcast over the columns of the coefficient in Python
In this article, we will be looking toward the approach to evaluating a Hermite series at points x broadcast over the columns of the coefficient in Python and NumPy. Example: Array: [1,2,3,4,5],[6,7,8,9,10]] Result: [ 73. 100. 131. 166. 205.] Explanation: Hermite series at points x broadcast over the columns Numpy np.hermeval() method To evaluate a
3 min read
Evaluate a Polynomial at Points x Broadcast Over the Columns of the Coefficient in Python using NumPy
In this article, we are going to see how to evaluate a polynomial at points x broadcast over the columns of the coefficient in Python using NumPy. numpy.polyval() methods The numpy numpy.polynomial.polynomial.polyval() method is used to evaluate a polynomial at points x broadcast over the columns of the coefficient in python. Calculate the value of
4 min read
Evaluate a Hermite_e series at points x broadcast over the columns of the coefficient in Python
In this article, we will cover how to evaluate a Hermite_e series at points x broadcast over the columns of the coefficient in Python using NumPy. ExampleInput: [1 2 3 4 5] Output: [ -3. 1077.] Explanation: Hermite_e series at input points.hermite_e.hermeval method To evaluate a Hermite_e series at points x with a multidimensional coefficient array
2 min read
Use for Loop That Loops Over a Sequence in Python
In this article, we are going to discuss how for loop is used to iterate over a sequence in Python. Python programming is very simple as it provides various methods and keywords that help programmers to implement the logic of code in fewer lines. Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, s
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg