No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python List Comprehension with Multiple Lists

by Khaleel O.
July 23, 2021
in Python
Reading Time: 4 mins read
A A
python list comprehension two lists
Python List Comprehension With Multiple Lists

In this tutorial we will show you how to use python list comprehension with two or more lists.

We can use the zip function. See the below example:

listA = [1,2,3,4]
listB = [5,6,7,8]

listC = [ A * B for A,B in zip(listA,listB)]
print(listC)

#Output
#[5, 12, 21, 32]

Let’s explain what is going on here:

  1. We define our two lists listA and listB. Both contain numbers only.
  2. Our list comprehension has the job of finding the product of the nth elements of listA and listB lists.
  3. The zip() function in Python accepts iterables (lists, dataframes, dictionaries etc.) and returns a zip object which is itself an iterator. This iterator generates a series of tuples containing elements from each iterable supplied in the original function, in the order they were supplied. The first tuple is the first element of each iterable, the second tuple is the second element of each iterable and so on. The zip() function is evaluated left-to-right.
  4. Our list comprehension returns listC which is a list of the products of each element of the two lists. The product of the 1st element of each list, the product of the 2nd element and so on. A is the iterator variable for listA, B is the iterator variable for listB. Because we want the product of the nth element in each list our output expression must be A*B, which gives us the product that we are looking for.

Let’s do another example with a pandas dataframe.

import pandas as pd

data = {'Country Name': ['Sundar','Jamal','Mark','Jenny','Bob'],
        'Year 1 Income':[250555,100300,45000,66000,1400000],
        'Year 2 Income':[250000,110300,45000,0,2400000]}

df = pd.DataFrame(data)

listD = [ B - A  for A,B in zip(df["Year 1 Income"],df["Year 2 Income"])]

print(listD)

#Output
#[-555, 10000, 0, -66000, 1000000]

So using zip() works on dataframes also because dataframes are an iterable object. In the above example we used the list comprehension to calculate the difference in income between two years for 5 people. We simply found the difference between Year 1 Income and Year 2 Income for each person using our list comprehension.

zip() can work on more than two lists also. See below:

listE = [1,2,3,4]
listF = [5,6,7,8]
listG = [9,10,11,12]

listH = [ E+F+G for E,F,G in zip(listE,listF,listG)]

print(listH)

#Output
#[15, 18, 21, 24]

In the above we used 3 lists in our zip() function: ListE, ListF and ListG. Our list comprehension used the iterator variables E, F and G in the expression E+F+G to give us the sum of nth elements of 3 different lists. Our output is a list of 4 elements, as expected.

The above example used lists with the same number of elements in the zip() function. If they were not of the same length, the zip() function iterator would have stopped when the shortest input iterable was exhausted. Please remember this when using lists of different lengths!

Finally, we don’t have to use the zip() function. We can use nested for-loops in our list comprehension. It all depends on the problem we are trying to solve. For example, if we want to find all of the possible permutations of two different lists we can do the following:

listI = [1,2,3,4]
listJ = [5,6,7,8]

listK = [[I, J] for I in listI for J in listJ]

print(listK)

#Output
#[[1, 5], [1, 6], [1, 7], [1, 8], [2, 5], [2, 6], [2, 7], [2, 8], [3, 5], [3, 6], [3, 7], [3, 8], [4, 5], [4, 6], [4, 7], [4, 8]]

So our nested for-loop in our list comprehension allowed us to generate a list of all permutations of numbers from two separate lists. We could have alternatively done this with a normal nested for-loop in the following way:

listI = [1,2,3,4]
listJ = [5,6,7,8]

listL=[]
x=[]

for I in listI:
    for J in listJ:
        listL.append([I,J])

print(listL)

#Output
#[[1, 5], [1, 6], [1, 7], [1, 8], [2, 5], [2, 6], [2, 7], [2, 8], [3, 5], [3, 6], [3, 7], [3, 8], [4, 5], [4, 6], [4, 7], [4, 8]]

The above nested loops work the same but list comprehensions, as we have seen, require less code and are more readable.

Find the full source code HERE and other great tutorial on list comprehensions HERE. Thanks for reading. 👌👌👌

Tags: dataframelist comprehension
Previous Post

Python List Comprehension with DataFrames – Part 2

Next Post

Python List Comprehension Nested For Loops

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy