Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Combine list with other list elements
Next article icon

Python List Comprehension With Two Lists

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

List comprehension allows us to generate new lists based on existing ones. Sometimes, we need to work with two lists together, performing operations or combining elements from both. Let's explore a few methods to use list comprehension with two lists.

Using zip() with List Comprehension

One of the most common tasks is to apply conditions to two lists. We can use list comprehension and zip() to filter or modify elements based on conditions.

Python
a = [1, 2, 3, 4] b = [5, 6, 7, 8]  # Create a new list where elements are from both lists, and the sum is greater than 10 result = [x + y for x, y in zip(a, b) if x + y > 10] print(result) 

Output
[12] 

Explanation:

  • zip(a, b) pairs corresponding elements from both lists.
  • The condition if x + y > 10 filters out pairs where the sum is not greater than 10.
  • The list comprehension creates a new list with the sum of x and y when the condition is met.

Note: zip() with List Comprehension can be used without using any conditional statements as well.

Let's explore some more ways to use list comprehension with two Lists

Table of Content

  • Using enumerate()
  • Using Custom Function
  • Using Nested Loops

Using enumerate()

In some cases we may want to access the index of the elements from the lists. enumerate() function can be used in list comprehension to iterate through both the index and the element of each list.

Python
a = ['Python', 'is', 'fun!'] b = ['Learn', 'with', 'GFG']  # Use enumerate to get the index and pair the elements from both lists result = [(i, x, y) for i, (x, y) in enumerate(zip(a, b))] print(result)  

Output
[(0, 'Python', 'Learn'), (1, 'is', 'with'), (2, 'fun!', 'GFG')] 

Explanation:

  • enumerate(zip(a, b)) gives both the index i and the pair (x, y) of corresponding elements from the lists a and b.
  • The list comprehension creates a new list containing tuples of the index and the elements from the two lists.

Using Custom Function

We can also use a custom function to process the elements from two lists. This can be helpful when we need to apply a specific operation or transformation to each pair of elements.

Python
a = [1, 2, 3] b = [4, 5, 6]  # Define a custom function to add two numbers def add_numbers(x, y):     return x + y  # Apply the custom function to each pair of elements result = [add_numbers(x, y) for x, y in zip(a, b)] print(result)  

Output
[5, 7, 9] 

Explanation:

  • zip(a, b) pairs corresponding elements from the two lists.
  • For each pair, the custom function add_numbers(x, y) is applied, which adds the two numbers.
  • The result is a list of summed values.

Using Nested Loops

List comprehension can also handle situations where we need to loop through each element of the first list and compare it with all elements of the second list. This can be done using nested loops within the list comprehension.

Python
a = [1, 2, 3] b = [4, 5]  # Create a new list that multiplies every element in a with every element in b result = [x * y for x in a for y in b] print(result)   

Output
[4, 5, 8, 10, 12, 15] 

Explanation:

  • The outer loop iterates over list a and the inner loop iterates over list b.
  • For each combination of elements x and y, the product x * y is added to the result list.

Next Article
Python - Combine list with other list elements

S

sahilm231199
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
  • python-basics
Practice Tags :
  • python
  • python-list

Similar Reads

  • Two For Loops in List Comprehension - Python
    List comprehension is a concise and readable way to create lists in Python. Using two for loops in list comprehension is a great way to handle nested iterations and generate complex lists. Using two for-loopsThis is the simplest and most efficient way to write two for loops in a list comprehension.
    2 min read
  • How to compare two lists in Python?
    In Python, there might be a situation where you might need to compare two lists which means checking if the lists are of the same length and if the elements of the lists are equal or not. Let us explore this with a simple example of comparing two lists. [GFGTABS] Python a = [1, 2, 3, 4, 5] b = [1, 2
    3 min read
  • Python List Comprehension Using If-Else
    List comprehension with if-else in Python is a concise way to apply conditional logic while creating a new list. It allows users to add elements based on specific conditions and even modify them before adding. Using if-else Inside List ComprehensionThis is the simplest and most efficient way to appl
    2 min read
  • Create a Dictionary with List Comprehension in Python
    The task of creating a dictionary with list comprehension in Python involves iterating through a sequence and generating key-value pairs in a concise manner. For example, given two lists, keys = ["name", "age", "city"] and values = ["Alice", 25, "New York"], we can pair corresponding elements using
    3 min read
  • Python - Combine list with other list elements
    Given two lists, combine list with each element of the other list. Examples: Input : test_list = [3, 5, 7], pair_list = ['Gfg', 'is', 'best'] Output : [([3, 5, 7], 'Gfg'), ([3, 5, 7], 'is'), ([3, 5, 7], 'best')] Explanation : All lists paired with each element from other list. Input : test_list = [3
    6 min read
  • How to Zip two lists of lists in Python?
    zip() function typically aggregates values from containers. However, there are cases where we need to merge multiple lists of lists. In this article, we will explore various efficient approaches to Zip two lists of lists in Python. List Comprehension provides a concise way to zip two lists of lists
    3 min read
  • Concatenate two list of lists Row-wise-Python
    The task of concatenate two lists of lists row-wise, meaning we merge corresponding sublists into a single sublist. For example, given a = [[4, 3], [1, 2]] and b = [[7, 5], [9, 6]], we pair elements at the same index: [4, 3] from a is combined with [7, 5] from b, resulting in [4, 3, 7, 5], and [1, 2
    3 min read
  • Python - Concatenate two lists element-wise
    In Python, concatenating two lists element-wise means merging their elements in pairs. This is useful when we need to combine data from two lists into one just like joining first names and last names to create full names. zip() function is one of the most efficient ways to combine two lists element-
    3 min read
  • How to Compare Two Iterators in Python
    Python iterators are powerful tools for traversing through sequences of elements efficiently. Sometimes, you may need to compare two iterators to determine their equality or to find their differences. In this article, we will explore different approaches to compare two iterators in Python. Compare T
    3 min read
  • Python Programs Combining Lists with Sets
    Lists maintain order and allow duplicate elements, while sets are unordered collections of unique elements. Combining these two structures enables efficient data processing, such as removing duplicates, checking subsets, converting between formats and performing set operations. This collection of Py
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences