Python | Cartesian product of string elements
Last Updated :
09 May, 2023
Sometimes, while working with Python strings, we can have problem when we have data in a string that is a comma or any delim separated. We might want to perform a cartesian product with other similar strings to get all possible pairs of data. Let us discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + split()
This task can be performed using list comprehension. In this, we perform the task of extracting individual elements using split(). The task of list comprehension is to form pairs.
Python3
# Python3 code to demonstrate working of
# Cartesian product of string elements
# Using split() + list comprehension
# Initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
# Printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Cartesian product of string elements
# Using split() + list comprehension
res = [sub1 + sub2 for sub1 in test_str1.split(", ")
for sub2 in test_str2.split(", ")]
# Printing result
print("Cartesian product list : " + str(res))
Output : The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']
Method #2: Using List comprehension + product()
The combination of the above functions can be used to perform this task. In this, we employ product() in place of nested comprehension to perform the task of pairing.
Python3
# Python3 code to demonstrate working of
# Cartesian product of string elements
# Using product() + list comprehension
from itertools import product
# initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Cartesian product of string elements
# Using product() + list comprehension
res = [sub1 + sub2 for sub1,
sub2 in product(test_str1.split(", "), test_str2.split(", "))]
# printing result
print("Cartesian product list : " + str(res))
Output : The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']
Method 3: Using nested for loops
- Create two lists by splitting the input strings using the split() method.
- Initialize an empty list to store the cartesian product of the strings.
- Use two nested for loops to iterate through each element of the two lists and concatenate them.
- Append the concatenated string to the empty list created in step 2.
- Return the list of cartesian product strings.
Python3
# Python3 code to demonstrate working of
# Cartesian product of string elements
# using nested for loops
# initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Creating two lists by splitting input strings
list1 = test_str1.split(", ")
list2 = test_str2.split(", ")
# initializing empty list to store cartesian product of strings
cartesian_product = []
# Using nested for loops to iterate through each element of the two lists and concatenate them.
for word1 in list1:
for word2 in list2:
cartesian_product.append(word1 + word2)
# printing result
print("Cartesian product list : " + str(cartesian_product))
OutputThe original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']
Time Complexity: O(n^2)
The nested for loop iterates through all the elements of both the lists, so the time complexity will be O(n^2), where n is the length of the input lists.
Auxiliary Space: O(n^2)
The space required by this method is O(n^2) because we are storing all the possible combinations in the cartesian_product list.
Method #4: Using itertools.product()
Step-by-step approach:
- Import the itertools module which provides various tools for creating iterators.
- Initialize the strings
- Split the strings into lists using the split() method and strip any whitespaces
- Use the product() function from itertools to generate the Cartesian product of the two lists
- Flatten the resulting list of tuples into a single list
- Print the final result
Python3
# Python3 code to demonstrate working of
# Cartesian product of string elements
# using itertools.product()
# importing itertools module
from itertools import product
# initializing strings
test_str1 = "gfg, is, best"
test_str2 = "for, all, geeks"
# Splitting strings into lists
list1 = [word.strip() for word in test_str1.split(',')]
list2 = [word.strip() for word in test_str2.split(',')]
# Using itertools.product() to generate Cartesian product
cartesian_product = list(product(list1, list2))
# Flattening the list of tuples into a single list
cartesian_product = [word1 + word2 for word1, word2 in cartesian_product]
# printing result
print("Cartesian product list : " + str(cartesian_product))
OutputCartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']
The time complexity of this method is O(n*m), where n is the length of the first list and m is the length of the second list.
The auxiliary space required by this method is O(n*m), as we store all possible combinations of elements from both lists in the cartesian_product list.
Similar Reads
Python - String Integer Product Sometimes, while working with data, we can have a problem in which we receive a series of lists with data in string format, which we wish to find the product of each string list integer. Letâs discuss certain ways in which this task can be performed. Method #1: Using loop + int()This is the brute fo
4 min read
Python - Product of elements using Index list Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and then perform the multipl
7 min read
Construct Cartesian Product Tuple list - Python The task of constructing the Cartesian product of tuple lists in Python involves iterating through multiple tuples and generating all possible ordered combinations of their elements. For example, given a list of tuples a = [(1, 2), ('A', 'B'), ('X', 'Y')], the goal is to produce a list of all possib
3 min read
Create a List of Strings in Python Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Concatenate all Elements of a List into a String - Python We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day".Using str.join()str.join()
2 min read
Python Program To Get Minimum Elements For String Construction Given a String, the task is to write a Python program to count the minimum elements required to form a string from list elements. Input : test_list = ["geek", "ring", "sfor", "ok", "woke"], tar_str = "working" Output : 2 Explanation : working can be formed using woke and ring. Input : test_list = ["
3 min read
List of strings in Python A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Python - Suffix Product in list We are given a list of numbers, and our task is to compute the suffix product for each position in the list. The suffix product at any index is the product of all elements to the right, including the element at that index. For example, given a = [2, 3, 4, 5], the suffix products would be [120, 60, 2
2 min read
Python | Pair Kth character with each element Sometimes, while working with Python, we can have a problem in which we need to perform the pairing of each character with every other in String. This can have application in many domains including web development and day-day. Lets discuss certain ways in which this task can be performed. Method #1
4 min read