Python - All possible concatenations in String List
Last Updated :
05 Apr, 2023
Sometimes, while working with String lists, we can have a problem in which we need to perform all possible concatenations of all the strings that occur in list. This kind of problem can occur in domains such as day-day programming and school programming.
Let's discuss a way in which this task can be performed.
Input : test_list = ['Gfg', 'Best']
Output : ['Gfg', 'Best', 'GfgBest', 'BestGfg']
Input : test_list = ['Gfg']
Output : ['Gfg']
Method 1: Using permutations() + join() + loop
The combination of above functions can be used to solve this problem. In this, we perform the task of concatenation using join() and all possible combination extraction using permutations().
Python3
# Python3 code to demonstrate working of
# All possible concatenations in String List
# Using permutations() + loop
from itertools import permutations
# initializing list
test_list = ['Gfg', 'is', 'Best']
# printing original list
print("The original list : " + str(test_list))
# All possible concatenations in String List
# Using permutations() + loop
temp = []
for idx in range(1, len(test_list) + 1):
temp.extend(list(permutations(test_list, idx)))
res = []
for ele in temp:
res.append("".join(ele))
# printing result
print("All String combinations : " + str(res))
OutputThe original list : ['Gfg', 'is', 'Best']
All String combinations : ['Gfg', 'is', 'Best', 'Gfgis', 'GfgBest', 'isGfg', 'isBest', 'BestGfg', 'Bestis', 'GfgisBest', 'GfgBestis', 'isGfgBest', 'isBestGfg', 'BestGfgis', 'BestisGfg']
Time complexity: O(n*n!) where n is the length of the input list.
Auxiliary Space: O(n*n!) where n is the length of the input list. The space complexity is dominated by the number of permutations that are generated and stored in the temporary list temp.
Method - 2: Using recursion and concatenation:
Approach:
- Define a helper function helper(lst, i, j) that takes the input list lst and two indices i and j and performs the following steps:
- If i is equal to the length of the list lst, then we have reached the end of the list and we return a list containing the string at index j.
- If j is equal to the length of the list lst, then we have reached the end of a pass through the list and need to move on to the next index i by calling the helper function again with i+1 and 0 as the new indices.
- If i and j are not equal, then we concatenate the strings at indices i and j and add the resulting string to a list, along with the results of a recursive call to the helper function with the same i and j+1 indices.
- If i and j are equal, then we simply call the helper function again with the same i and j+1 indices.
- Finally, we return the results of calling the helper function with initial indices 0 and 0, concatenated with the original input list.
Below is the implementation of the above approach:
Python3
# Python program for the above approach
# Function to generate all possible combination
# using recursion
def concat_list4(lst):
def helper(lst, i, j):
if i == len(lst):
return [lst[j]]
if j == len(lst):
return helper(lst, i+1, 0)
if i != j:
return [lst[i] + lst[j]] + helper(lst, i, j+1)
return helper(lst, i, j+1)
return helper(lst, 0, 0) + lst
# Driver Code
# Test case 1
test_list1 = ['Gfg', 'Best']
output1 = concat_list4(test_list1)
print(output1) # Output: ['Gfg', 'Best', 'GfgBest', 'BestGfg']
# Test case 2
test_list2 = ['Gfg']
output2 = concat_list4(test_list2)
print(output2) # Output: ['Gfg']
Output['GfgBest', 'BestGfg', 'Gfg', 'Gfg', 'Best']
['Gfg', 'Gfg']
Time Complexity: O(N2)
Space Complexity: O(N2)
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read