Open In App

Python program to concatenate every elements across lists

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given 2 lists, perform concatenations of all strings with each other across list.

Input : test_list1 = [“gfg”, “is”, “best”], test_list2 = [“love”, “CS”] 
Output : [‘gfg love’, ‘gfg CS’, ‘is love’, ‘is CS’, ‘best love’, ‘best CS’] 
Explanation : All strings are coupled with one another.

Input : test_list1 = [“gfg”, “best”], test_list2 = [“love”, “CS”] 
Output : [‘gfg love’, ‘gfg CS’, ‘best love’, ‘best CS’] 
Explanation : All strings are coupled with one another. 
 

Method #1: Using list comprehension

In this, we form pairs with each using list comprehension and then perform task of concatenation using another list comprehension.

Python3




# Python3 code to demonstrate working of
# All elements concatenation across lists
# Using list comprehension
 
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# forming pairs
temp = [(a, b) for a in test_list1 for b in test_list2]
 
# performing concatenation
res = [x + ' ' + y for (x, y) in temp]
 
# printing result
print("The paired combinations : " + str(res))


Output:

The original list 1 is : [‘gfg’, ‘is’, ‘best’] The original list 2 is : [‘love’, ‘CS’] The paired combinations : [‘gfg love’, ‘gfg CS’, ‘is love’, ‘is CS’, ‘best love’, ‘best CS’]

Time Complexity: O(n2) -> two for loops

Space Complexity: O(n)

Method #2 : Using product() + list comprehension

In this, we perform task of forming combination using product() and list comprehension performs the task of concatenation.

Python3




# Python3 code to demonstrate working of
# All elements concatenation across lists
# Using product() + list comprehension
from itertools import product
 
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# concatenation using formatting and pairing using product
res = ['%s %s' % (ele[0], ele[1]) for ele in product(test_list1, test_list2)]
 
# printing result
print("The paired combinations : " + str(res))


Output:

The original list 1 is : [‘gfg’, ‘is’, ‘best’] The original list 2 is : [‘love’, ‘CS’] The paired combinations : [‘gfg love’, ‘gfg CS’, ‘is love’, ‘is CS’, ‘best love’, ‘best CS’]

Time Complexity: O(n2) -> time complexity of product is O(n) and a for loop, O(n2)

Space Complexity: O(n)

Method #3: Using map and join

In this approach, we use map function to perform the task of concatenation and then join the resultant strings.

Python3




# Python3 code to demonstrate working of
# All elements concatenation across lists
# Using map() and join()
from itertools import product
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# concatenation using map() and join()
res = list(map(' '.join, product(test_list1, test_list2)))
  
# printing result
print("The paired combinations : " + str(res))


Output

The original list 1 is : ['gfg', 'is', 'best']
The original list 2 is : ['love', 'CS']
The paired combinations : ['gfg love', 'gfg CS', 'is love', 'is CS', 'best love', 'best CS']

Time Complexity: O(n2) -> time complexity of product is O(n) and a map function call O(n)

Auxiliary Space: O(n)

Method #4: Using itertools.product() and str.join()

  • Import the itertools module, which provides various functions to work with iterators.
  • Initialize two lists test_list1 and test_list2 with the desired elements.
  • Use itertools.product() function to form all possible pairs of elements from test_list1 and test_list2. This function returns an iterator that generates the pairs one at a time.
  • Store the iterator in a temporary variable called temp.
  • Iterate over the temp iterator and for each pair, join the elements using a space separator (‘ ‘) and append the result to a list called res.
  • Print the final result by converting the res list to a string using str() and passing it to the print() function

Python3




import itertools
 
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
 
# forming pairs
temp = itertools.product(test_list1, test_list2)
 
# performing concatenation
res = [' '.join(pair) for pair in temp]
 
# printing result
print("The paired combinations : " + str(res))


Output

The paired combinations : ['gfg love', 'gfg CS', 'is love', 'is CS', 'best love', 'best CS']

Time complexity: O(n^2), where n is the length of the longer list (since we form all possible pairs).
Auxiliary space: O(n^2) for the temp list, since we need to store all the pairs.



Previous Article
Next Article

Similar Reads

Python - Values frequency across Dictionaries lists
Given two list of dictionaries, compute frequency corresponding to each value in dictionary 1 to second. Input : test_list1 = [{"Gfg" : 6}, {"best" : 10}], test_list2 = [{"a" : 6}, {"b" : 10}, {"d" : 6}}] Output : {'Gfg': 2, 'best': 1} Explanation : 6 has 2 occurrence in 2nd list, 10 has 1. Input : test_list1 = [{"Gfg" : 6}], test_list2 = [{"a" : 6
6 min read
Python - Disjoint Strings across Lists
Given two lists, extract all the string pairs which are disjoint across i.e. which don't have any character in common. Input : test_list1 = ["haritha", "is", "best"], test_list2 = ["she", "loves", "papaya"] Output : [('haritha', 'loves'), ('is', 'papaya'), ('best', 'papaya')] Explanation : "is" and "papaya" has no character in common. Input : test_
4 min read
Python - Maximum difference across lists
Given two lists, the task is to write a Python program to find maximum difference among like index elements. Examples: Input : test_list1 = [3, 4, 2, 1, 7], test_list2 = [6, 2, 1, 9, 1]Output : 8Explanation : 9 - 1 = 8 is maximum difference across lists in same index. Input : test_list1 = [3, 4, 2, 1, 17], test_list2 = [6, 2, 1, 9, 1]Output : 16Exp
4 min read
Python | Concatenate two lists element-wise
Sometimes we come across this type of problem in which we require to leave each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compreh
4 min read
Python | Concatenate dictionary value lists
Sometimes, while working with dictionaries, we might have a problem in which we have lists as it's value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using sum() + values() This is the most recommended m
5 min read
Python - Concatenate two list of lists Row-wise
Given two matrices, the task is to write a Python program to add elements to each row from initial matrix. Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1, 3], [9, 3, 5, 7], [8]] Output : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]] Explanation : Matrix is row wise merged. Input : test_list1 = [[4, 3, 5,], [1, 2,
5 min read
Python - Multiplication across Like Keys Value list elements
Given two dictionaries with value lists, perform element wise like keys multiplication. Input : test_dict1 = {"Gfg" : [4, 6], "Best" : [8, 6], "is" : [9, 3]}, test_dict2 = {"Gfg": [8, 4], "Best" : [6, 3], "is" : [9, 8]} Output : {'Gfg': [32, 24], 'Best': [48, 18], 'is': [81, 24]} Explanation : 4 * 8 = 32, 6 * 4 = 24 and so on, hence new list value.
9 min read
Python Program for Mirror of matrix across diagonal
Given a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in a way: swap the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. Print the 2-D array obtained in a matrix layout. Examples: Input : int mat[][] = {{1 2
4 min read
Python program to Concatenate all Elements of a List into a String
Given a list, the task is to write a Python program to concatenate all elements in a list into a string i.e. we are given a list of strings and we expect a result as the entire list is concatenated into a single sentence and printed as the output. Examples: Input: ['hello', 'geek', 'have', 'a', 'geeky', 'day'] Output: hello geek have a geeky dayUsi
3 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Practice Tags :