Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Merge list of tuple into list by joining the strings

Python | Merge list of tuple into list by joining the strings

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




# Python code to convert list of tuple into list
# by joining elements of tuple
 
# Input list initialisation
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# using join and list comprehension
Output = ['_'.join(temp) for temp in Input]
 
# printing output
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




# Python code to convert list of tuple into list
# by joining elements of tuple
 
# Input list initialisation
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# using map and join
Output = list(map('_'.join, Input))
 
# printing output
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.

  1. Define a recursive function tuple_to_list_recursive that takes an input list of tuples as its parameter.
  2. Check if the input list is empty. If it is, return an empty list.
  3. 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.
  4. Join the elements of the head tuple using the ‘_’ separator and add the result to a list.
  5. Call tuple_to_list_recursive recursively with the tail list as the input parameter.
  6. Concatenate the result of step 4 with the result of step 5.
  7. 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)
#this code contributed by tvsk.


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




# Python code to convert list of tuple into list
# by joining elements of tuple
 
# Input list initialization
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# Using a for loop to join elements of tuples
Output = []
for temp in Input:
    Output.append('_'.join(temp))
 
# Printing output
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:

  1. Import the reduce function from the functools module.
  2. Initialize the input list Input with the given tuples.
  3. Use the reduce function and a lambda function to join the elements of each tuple and add them to the output list.
  4. 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.
  5. Print the output list.

Python3




# Importing reduce function from functools module
from functools import reduce
 
# Input list initialization
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# Using reduce() function and lambda function to join the elements of each tuple and add them to the output list
Output = reduce(lambda lst, tpl: lst + [f"{tpl[0]}_{tpl[1]}"], Input, [])
 
# Printing output
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. 

  1. We first use the itertools.chain() function to flatten the list of tuples into a single iterable. 
  2. 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.
  3. We then use the map() function to apply the _.join() method to each element in the flattened iterable.
  4. The map() function returns a map object, which we convert to a list using the list() function.
  5. 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. 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments