Python | Merge list of tuple into list by joining the strings
Last Updated :
17 Apr, 2023
Sometimes, we are required to convert list of tuples into a list by joining two element of tuple by a special character. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. Let’s try to understand it better with code examples.
Method 1: Using list comprehension and join()
Python3
Input = [( 'Hello' , 'There' ), ( 'Namastey' , 'India' ), ( 'Incredible' , 'India' )]
Output = [ '_' .join(temp) for temp in Input ]
print (Output)
|
Output:
['Hello_There', 'Namastey_India', 'Incredible_India']
Time complexity: O(n), where n is the number of tuples in the input list. This is because the code iterates through each tuple in the list once.
Auxiliary space: O(n), where n is the number of tuples in the input list. This is because the code creates a new list of the same length as the input list to store the output.
Method 2: Using map and join()
Python3
Input = [( 'Hello' , 'There' ), ( 'Namastey' , 'India' ), ( 'Incredible' , 'India' )]
Output = list ( map ( '_' .join, Input ))
print (Output)
|
Output:
['Hello_There', 'Namastey_India', 'Incredible_India']
The time complexity of the given program is O(n), where n is the length of the input list.
The auxiliary space used by the program is O(n), where n is the length of the input list.
Method#3: Using Recursive method.
- Define a recursive function tuple_to_list_recursive that takes an input list of tuples as its parameter.
- Check if the input list is empty. If it is, return an empty list.
- If the input list is not empty, take the first tuple from the list using the head variable and the remaining tuples using the tail variable.
- Join the elements of the head tuple using the ‘_’ separator and add the result to a list.
- Call tuple_to_list_recursive recursively with the tail list as the input parameter.
- Concatenate the result of step 4 with the result of step 5.
- Return the concatenated list.
Python3
def tuple_to_list_recursive(input_list):
if not input_list:
return []
else :
head, * tail = input_list
return [ '_' .join(head)] + tuple_to_list_recursive(tail)
Input = [( 'Hello' , 'There' ), ( 'Namastey' , 'India' ), ( 'Incredible' , 'India' )]
Output = tuple_to_list_recursive( Input )
print (Output)
|
Output
['Hello_There', 'Namastey_India', 'Incredible_India']
Time complexity: The time complexity of this recursive method is O(n), where n is the number of tuples in the input list. This is because the function processes each tuple in the list exactly once.
Auxiliary space: The auxiliary space complexity of this method is O(n), where n is the number of tuples in the input list. This is because the function creates a new list of length n to store the result, and the recursive calls to the function use O(n) stack space due to the function call stack.
Method 4: Using a for loop
Step-by-step approach:
- Initialize the input list of tuples.
- Create an empty list called Output to store the converted tuples.
- Use a for loop to iterate through each tuple in the Input list.
- Within the loop, use the join() method to join the elements of the tuple using ‘_’ as the separator and append the joined string to the Output list.
- Print the Output list.
Below is the implementation of the above approach:
Python3
Input = [( 'Hello' , 'There' ), ( 'Namastey' , 'India' ), ( 'Incredible' , 'India' )]
Output = []
for temp in Input :
Output.append( '_' .join(temp))
print (Output)
|
Output
['Hello_There', 'Namastey_India', 'Incredible_India']
Time Complexity: O(n), where n is the number of tuples in the Input list, since we only need to iterate through the list once.
Auxiliary Space: O(n), since we need to store the converted tuples in the Output list.
Method 5: Using reduce() function and lambda function
step-by-step approach of the above program:
- Import the reduce function from the functools module.
- Initialize the input list Input with the given tuples.
- Use the reduce function and a lambda function to join the elements of each tuple and add them to the output list.
- The reduce function applies the lambda function on the Input list by taking two arguments at a time from the list and concatenating them using _ separator. The output is a single list with all the joined elements.
- Print the output list.
Python3
from functools import reduce
Input = [( 'Hello' , 'There' ), ( 'Namastey' , 'India' ), ( 'Incredible' , 'India' )]
Output = reduce ( lambda lst, tpl: lst + [f "{tpl[0]}_{tpl[1]}" ], Input , [])
print (Output)
|
Output
['Hello_There', 'Namastey_India', 'Incredible_India']
Time complexity: O(n)
Auxiliary space: O(n)
Method 6: Using itertools.chain() and map()
We can also use the itertools.chain() function and map() function to flatten the list of tuples and then join the elements.
- We first use the itertools.chain() function to flatten the list of tuples into a single iterable.
- The chain.from_iterable() method takes an iterable of iterables and returns a single iterable that contains all the elements from all the iterables. In this case, we pass the input list Input to chain.from_iterable() to flatten it.
- We then use the map() function to apply the _.join() method to each element in the flattened iterable.
- The map() function returns a map object, which we convert to a list using the list() function.
- The resulting Output list contains the joined elements of the original list of tuples.
Python3
from itertools import chain
Input = [( 'Hello' , 'There' ), ( 'Namastey' , 'India' ), ( 'Incredible' , 'India' )]
Output = list ( map ( '_' .join, chain.from_iterable( Input )))
print (Output)
|
Output
['H_e_l_l_o', 'T_h_e_r_e', 'N_a_m_a_s_t_e_y', 'I_n_d_i_a', 'I_n_c_r_e_d_i_b_l_e', 'I_n_d_i_a']
The time complexity of this method is O(n), where n is the total number of elements in the input list of tuples.
The auxiliary space of this method is O(n), where n is the total number of elements in the input list of tuples.
Similar Reads
Convert list of strings to list of tuples in Python
Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
5 min read
Convert List of Tuples to List of Strings - Python
The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings. For example, gi
3 min read
Python | Merge two lists into list of tuples
The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi
3 min read
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read
Convert List Of Tuples To Json String in Python
We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python. Convert List Of Tuples To Json String in PythonBelow, are the methods of Convert List Of Tuples To Json St
3 min read
Python - Convert List of Integers to a List of Strings
We are given a list of integers and our task is to convert each integer into its string representation. For example, if we have a list like [1, 2, 3] then the output should be ['1', '2', '3']. In Python, there are multiple ways to do this efficiently, some of them are: using functions like map(), re
3 min read
Python | Ways to merge strings into list
Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requir
4 min read
Convert List of Tuples To Multiple Lists in Python
When working with data in Python, it's common to encounter situations where we need to convert a list of tuples into separate lists. For example, if we have a list of tuples where each tuple represents a pair of related data points, we may want to split this into individual lists for easier processi
4 min read
Python | Convert List of lists to list of Strings
Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
4 min read
Python | Find number of lists in a tuple
Given a tuple of lists, the task is to find number of lists in a tuple. This is a very basic problem but can be useful while making some utility application. Method #1: Using len C/C++ Code # Python code to find number of list in a tuple # Initial list Input1 = ([1, 2, 3, 4], [5, 6, 7, 8]) Input2 =
4 min read