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 | Merge two list of lists according to first element
Next article icon

Python – Combine list with other list elements

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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, 5, 7], pair_list = [‘Gfg’, ‘best’] 
Output : [([3, 5, 7], ‘Gfg’), ([3, 5, 7], ‘best’)] 
Explanation : All lists paired with each element from other list. 

Method #1 : Using zip() + len() + list()

In this, we pair each element using zip(), with all the elements of other list using len(), and picking each element at once.

Python3




# Python3 code to demonstrate working of
# Combine list with other list elements
# Using zip() + len() + list()
 
# initializing list
test_list = [3, 5, 7, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
 
# using zip() to pair element with pair list size
res = list(zip([test_list] * len(pair_list), pair_list))
 
# printing result
print("The paired list : " + str(res))
 
 
Output
The original list is : [3, 5, 7, 9] The paired list : [([3, 5, 7, 9], 'Gfg'), ([3, 5, 7, 9], 'is'), ([3, 5, 7, 9], 'best')]

Time Complexity: O(n) where n is the number of elements in the list “test_list”.  zip() + len() + list() performs n number of operations.
Auxiliary Space: O(n), extra space of size n is required

Method #2 : Using product()

In this, we pair the elements using product(), and map each list with each element in pair list.

Python3




# Python3 code to demonstrate working of
# Combine list with other list elements
# Using product()
from itertools import product
 
# initializing list
test_list = [3, 5, 7, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
 
# product() performs pairing of elements
res = list(product([test_list], pair_list))
 
# printing result
print("The paired list : " + str(res))
 
 
Output
The original list is : [3, 5, 7, 9] The paired list : [([3, 5, 7, 9], 'Gfg'), ([3, 5, 7, 9], 'is'), ([3, 5, 7, 9], 'best')]

Method #3:  Using append() and tuple() methods

Python3




# Python3 code to demonstrate working of
# Combine list with other list elements
 
# initializing list
test_list = [3, 5, 7, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
 
res = []
for i in pair_list:
    x = []
    x.append(test_list)
    x.append(i)
    x = tuple(x)
    res.append(x)
# printing result
print("The paired list : " + str(res))
 
 
Output
The original list is : [3, 5, 7, 9] The paired list : [([3, 5, 7, 9], 'Gfg'), ([3, 5, 7, 9], 'is'), ([3, 5, 7, 9], 'best')]

Time Complexity: O(n), where n is length of pair_list.

Auxiliary Space: O(n), where n is length of res list to store result.

Method #4: Using map() function and lambda function

Step-by-step algorithm:

  1. Define two lists, test_list and pair_list.
  2. Use map() and lambda to create a list of tuples where each tuple contains the entire test_list and one element from pair_list.
  3. Convert the resulting map object to a list and store it in the variable res.
  4. Print the original list and the paired list.

Python3




# define the test_list and pair_list
test_list = [3, 5, 7, 9]
pair_list = ['Gfg', 'is', 'best']
 
# use map() and lambda to create a list of tuples where each tuple contains the entire test_list and one element from pair_list
res = list(map(lambda x: (test_list, x), pair_list))
 
# printing original list and paired list
print("The original list is : " + str(test_list))
print("The paired list : " + str(res))
 
 
Output
The original list is : [3, 5, 7, 9] The paired list : [([3, 5, 7, 9], 'Gfg'), ([3, 5, 7, 9], 'is'), ([3, 5, 7, 9], 'best')]

Time complexity:

The time complexity of the algorithm is O(n), where n is the length of pair_list. This is because the lambda function is executed for each element in pair_list, and the map() function has a time complexity of O(n).
Auxiliary space:

The auxiliary space complexity of the algorithm is O(n), where n is the length of pair_list. This is because the list res has a space complexity of O(n), which is the same as the space complexity of pair_list.

Method #5: Using reduce():

  1. Initialize the original list test_list and print it.
  2. Initialize the pair list pair_list.
  3. Define the combine lambda function, which takes two arguments acc and elem, and returns a new list of pairs. If acc is non-empty, it pairs each element of pair_list with each element of acc and appends the resulting pairs to acc. If acc is empty, it pairs each element of pair_list with elem and returns the resulting pairs. The lambda function is defined using a ternary operator.
  4. Apply the reduce method to the list [test_list] using the combine lambda function and an empty list [] as the initial value of the accumulator. The reduce method applies the combine function to the accumulator and the first element of the list, then applies it again to the result and the second element of the list, and so on, until all elements of the list have been processed. The final result is a list of pairs obtained by pairing each element of pair_list with each element of test_list.
  5. Print the resulting paired list res.

Python3




# Python3 code to demonstrate working of
# Combine list with other list elements
# Using reduce()
 
# import reduce from functools module
from functools import reduce
 
# initializing list
test_list = [3, 5, 7, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
 
# define lambda function to combine elements
combine = lambda acc, elem: acc + [(elem1, elem2) for elem1 in acc[-1] for elem2 in pair_list] if acc else [(elem, elem2) for elem2 in pair_list]
 
# apply lambda function to the list using reduce method
res = reduce(combine, [test_list], [])
 
# printing result
print("The paired list : " + str(res))
#This code is contributed by Jyothi pinjala.
 
 
Output
The original list is : [3, 5, 7, 9] The paired list : [([3, 5, 7, 9], 'Gfg'), ([3, 5, 7, 9], 'is'), ([3, 5, 7, 9], 'best')] 

The time complexity: O(n * m^2), where n is the length of test_list and m is the length of pair_list. 

The space complexity : O(n * m^2), due to the list of pairs that is generated as a result.



Next Article
Python | Merge two list of lists according to first element
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Find common elements in list of lists
    The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
    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 List Comprehension With Two Lists
    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 ComprehensionOne of the mo
    3 min read
  • Python | Merge two list of lists according to first element
    Given two list of lists of equal length, write a Python program to merge the given two lists, according to the first common element of each sublist. Examples: Input : lst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']] lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']] Output : [[1, 'Alice', 'Delhi'],
    6 min read
  • Python - Append Missing Elements from Other List
    We are given two lists, and our task is to append elements from the second list to the first list, but only if they are not already present. This ensures that the first list contains all unique elements from both lists without duplicates. For example, if a = [1, 2, 3] and b = [2, 3, 4, 5], the resul
    3 min read
  • Python | Add list elements with a multi-list based on index
    Given two lists, one is a simple list and second is a multi-list, the task is to add both lists based on index. Example: Input: List = [1, 2, 3, 4, 5, 6] List of list = [[0], [0, 1, 2], [0, 1], [0, 1], [0, 1, 2], [0]] Output: [[1], [2, 3, 4], [3, 4], [4, 5], [5, 6, 7], [6]] Explanation: [1] = [1+0]
    5 min read
  • Python - Operation to each element in list
    Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
    3 min read
  • How To Combine Multiple Lists Into One List Python
    Combining multiple lists into a single list is a common operation in Python, and there are various approaches to achieve this task. In this article, we will see how to combine multiple lists into one list in Python. Combine Multiple Lists Into One List PythonBelow are some of the ways by which we ca
    2 min read
  • Add Elements of Two Lists in Python
    Adding corresponding elements of two lists can be useful in various situations such as processing sensor data, combining multiple sets of results, or performing element-wise operations in scientific computing. List Comprehension allows us to perform the addition in one line of code. It provides us a
    3 min read
  • Python | Convert list of tuples into list
    In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
    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