Python - Concatenate Strings in the Given Order
Last Updated :
10 May, 2023
Given a String List and order list, perform string concatenation in a specific order.
Input : test_list = ["best", "Gfg", "for", "is"], sort_order = [1, 3, 0, 2]
Output : Gfgisbestfor
Explanation : Combined as per order of indices.
Input : test_list = ["best", "Gfg"], sort_order = [1, 0]
Output : Gfgbest
Explanation : Combined as per order of indices.
Method #1: Using loop
In this, we iterate order elements in the loop and perform concatenation of strings of the similar index in similar order.
Python3
# Python3 code to demonstrate working of
# Concatenate Strings in Order
# Using loop
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing join order
sort_order = [1, 3, 0, 2, 4]
res = ''
for order in sort_order:
# concatenating by order
res += test_list[order]
# printing result
print("Ordered concatenation : " + str(res))
OutputThe original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1) additional space is not needed
Method #2: Using join() + list comprehension
In this, we perform the task of concatenation using join(), list comprehension is used for iteration of order.
Python3
# Python3 code to demonstrate working of
# Concatenate Strings in Order
# Using join() + list comprehension
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing join order
sort_order = [1, 3, 0, 2, 4]
# join() performs concatenation
res = ''.join([test_list[order] for order in sort_order])
# printing result
print("Ordered concatenation : " + str(res))
OutputThe original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
Time Complexity: O(n)
Space Complexity: O(n)
Method #3: Using map()
Here's a different approach, which leverages the python map() function:
Python3
# Python3 code to demonstrate working of
# Concatenate Strings in Order
# Using map()
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing join order
sort_order = [1, 3, 0, 2, 4]
# using map() to get the concatenated string
res = ''.join(map(lambda x: test_list[x], sort_order))
# printing result
print("Ordered concatenation : " + str(res))
OutputThe original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
Time Complexity: O(n)
Auxiliary Space: O(n)
The code leverages the map() function to iterate over the sort_order list, and using a lambda function, it retrieves the corresponding string from the test_list. The join() function is then used to concatenate the retrieved strings into a single string.
Method 4: Using the zip() function and a generator expression
Step-by-step approach:
- The program begins by initializing a list named test_list with some strings.
- The print() function is used to display the original list.
- Next, another list named sort_order is initialized with a specific order in which the strings need to be concatenated.
- The zip() function is then used to map the values of test_list and sort_order together.
- A generator expression is used to iterate over the mapped values, where each value represents the index of the element in test_list in the order specified in sort_order.
- The join() function is then used to concatenate the strings in the order specified by the sort_order list.
- The final concatenated string is stored in a variable named res.
- Finally, the concatenated string is displayed using the print() function.
Python3
# Python3 code to demonstrate working of
# Concatenate Strings in Order
# Using zip() + generator expression
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing join order
sort_order = [1, 3, 0, 2, 4]
# using zip() to map values
# iterating over the generator expression
res = ''.join(test_list[i] for i in sort_order)
# printing result
print("Ordered concatenation : " + str(res))
OutputThe original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
Time complexity: O(n), where n is the length of the list and the sort_order array. Both of these are iterated over once.
Auxiliary space: O(1), since we only use constant extra space to store the intermediate result and no additional data structures are used
Method 5: Use the sorted() function with a custom key function.
Step-by-step approach:
- Initialize the list of strings.
- Initialize the order of concatenation.
- Define a custom key function that returns the index of the current string in the sort_order list.
- Use the sorted() function with the key function to sort the list of strings in the given order.
- Join the sorted list of strings using the join() method.
- Print the final result.
Python3
# Python3 code to demonstrate working of
# Concatenate Strings in Order
# Using sorted() function with custom key
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing join order
sort_order = [1, 3, 0, 2, 4]
# define a custom key function
def custom_key(item):
return sort_order.index(test_list.index(item))
# using sorted() with custom key to concatenate strings in order
res = ''.join(sorted(test_list, key=custom_key))
# printing result
print("Ordered concatenation : " + str(res))
OutputThe original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
Time complexity: O(nlogn) due to the use of sorted(),
Auxiliary space: O(n) for storing the sorted list of strings.
Similar Reads
Most efficient way to Concatenate Strings in Python
Concatenation is an operation that is very frequently used in various problems related to strings. There are multiple methods to concat strings in various languages. Python is also such a language that supports various string concatenation methods. But have you ever wondered which one is the most ef
3 min read
Python - Convert Dictionary to Concatenated String
In Python, sometimes we need to convert a dictionary into a concatenated string. The keys and values of the dictionary are combined in a specific format to produce the desired string output. For example, given the dictionary {'a': 1, 'b': 2, 'c': 3}, we may want the string "a:1, b:2, c:3". Let's dis
3 min read
Python - Concatenate Dictionary string values
The task of concatenating string values in a Python dictionary involves combining the values associated with the same key across multiple dictionaries. This operation allows us to merge string data in an efficient manner, especially when dealing with large datasets .For example, given two dictionari
4 min read
Python - String Matrix Concatenation
Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
4 min read
Python - Concatenate string rows in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the concatenation of rows of matrix in uneven sized matrix. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using joi
3 min read
Python - Concatenate Ranged Values in String list
Given list of strings, perform concatenation of ranged values from the Strings list. Input : test_list = ["abGFGcs", "cdforef", "asalloi"], i, j = 3, 5 Output : FGorll Explanation : All string sliced, FG, or and ll from all three strings and concatenated. Input : test_list = ["aGFGcs", "cforef", "aa
5 min read
Python program to Concatenate Kth index words of String
Given a string with words, concatenate the Kth index of each word. Input : test_str = 'geeksforgeeks best geeks', K = 3 Output : ktk Explanation : 3rd index of "geeksforgeeks" is k, "best" has 't' as 3rd element. Input : test_str = 'geeksforgeeks best geeks', K = 0 Output : gbg Method #1 : Using joi
4 min read
Python program to concatenate Strings around K
Given List of Strings, join all the strings which occurs around string K. Input : test_list = ["Gfg", "*", "is", "best", "*", "love", "gfg"], K = "*" Output : ['Gfg*is', 'best*love', 'gfg'] Explanation : All elements around * are joined.Input : test_list = ["Gfg", "$", "is", "best", "$", "love", "gf
5 min read
Python - Horizontal Concatenation of Multiline Strings
Horizontal concatenation of multiline strings involves merging corresponding lines from multiple strings side by side using methods like splitlines() and zip(). Tools like itertools.zip_longest() help handle unequal lengths by filling missing values, and list comprehensions format the result.Using z
3 min read
Python - Triple quote String concatenation
Sometimes, while working with Python Strings, we can have a problem in which we need to perform concatenation of Strings which are constructed by Triple quotes. This happens in cases we have multiline strings. This can have applications in many domains. Let us discuss certain ways in which this task
4 min read