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 - Print all common elements of two lists
Next article icon

Python program to get all unique combinations of two Lists

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal is to combine each item from first list with each item from second list in every possible unique way. If we want to get all possible combinations from two lists. Python’s itertools library has a function called a product that makes it easy to generate combinations of items from multiple lists.

Python
import itertools  a = ["a", "b"] b = [1, 2]  #It generate all possible combinations of elements from both lists # Convert the result into a list of tuples combinations = list(itertools.product(a, b))  print(combinations) 

Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)] 
  • itertools.product automatically creates the combinations of elements from both lists. We use list() to convert the result into a list of tuples.

There are other methods which can be used that are both fast and efficient :

Table of Content

  • Using itertools.permutations
  • Using a Nested Loop
  • Using List Comprehension

Using itertools.permutations

itertools.permutations function creates all possible permutations of a given list. We can combine this with zip to create unique combinations of two lists.

Python
import itertools  a = ["a", "b"] b = [1, 2]  # Generate all 2-length permuations of pairs by zipping lists combinations = list(itertools.permutations(zip(a, b), 2)) print(combinations) 

Output
[(('a', 1), ('b', 2)), (('b', 2), ('a', 1))] 
  • The zip(a, b) combines the two lists element-wise into pairs, and itertools.permutations then creates all possible orders of these pairs.
  • This method returns all unique permutations, including reversed combinations.

Using a Nested Loop

We can get all combinations is by using two loops. We can loop through each element in both lists and combine them.

Python
X = ["a", "b"] Y = [1, 2]  # Initialize an empty list  combinations = []  # Loop through each element in List_1 for x in X:     # Loop through each element in List_2     for y in Y:         combinations.append((x, y))  print(combinations) 

Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)] 

Using List Comprehension

If we have to write cleaner and shorter code, we can use list comprehension to achieve the same result. This is essentially the same thing as using loops but in a single line. It’s a concise way to combine elements.

Python
X = ["a", "b"] Y = [1, 2]  #list combination of all possible elemenst of two lists(X and Y) combinations = [(x, y) for x in X for y in Y]  print(combinations) 

Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)] 


Next Article
Python - Print all common elements of two lists
author
vanshgaur14866
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python-itertools
Practice Tags :
  • python

Similar Reads

  • Python List and Tuple Combination Programs
    Lists and tuples are two of the most commonly used data structures in Python. While lists are mutable and allow modifications, tuples are immutable and provide a stable structure for storing data. This article explores various programs related to list and tuple combinations, covering topics like: So
    6 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
  • Python | Program to count duplicates in a list of tuples
    Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a
    6 min read
  • Python - Print all common elements of two lists
    Finding common elements between two lists is a common operation in Python, especially in data comparison tasks. Python provides multiple ways to achieve this, from basic loops to set operations. Let's see how we can print all the common elements of two lists Using Set Intersection (Most Efficient)Th
    3 min read
  • Python - All Possible unique K size combinations till N
    Sometimes, while working with Python domain, we can have a problem in which we need to produce various combination of elements. This can be K sized unique combinations till N. This problem can have application in data domains and school programming. Let's discuss certain ways in which this task can
    4 min read
  • Python program to unique keys count for Value in Tuple List
    Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
    6 min read
  • Python - Get all numbers combinations in list
    Sometimes, while working with Python lists, we can have a problem in which we need to concatenate each number with other create new number. This kind of problem is peculiar but can have application in many domains such as day-day programming and gaming. Let's discuss certain ways in which this task
    3 min read
  • Python - All pair combinations of 2 tuples
    Sometimes, while working with Python tuples data, we can have a problem in which we need to extract all possible combination of 2 argument tuples. This kind of application can come in Data Science or gaming domains. Let's discuss certain ways in which this task can be performed. Input : test_tuple1
    6 min read
  • Python program to find all the Combinations in the list with the given condition
    Given a list with some elements being a list of optional elements. The task is to find all the possible combinations from all options. Examples: Input: test_list = [1,2,3] Output: [1], [1, 2], [1, 2, 3], [1, 3] [2], [2, 3], [3] Example 1: Get all possible combinations of a list’s elements using comb
    3 min read
  • Print all Possible Combinations from the Three Digits - Python
    The task of printing all possible combinations from three digits in Python involves generating all unique ways to arrange the digits, considering their order. For example, given the digits 1, 2, and 3, the goal is to produce all permutations such as [1, 2, 3], [1, 3, 2], [2, 1, 3], and so on. Using
    3 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