![]() |
VOOZH | about |
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()
['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()
['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.
['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:
Below is the implementation of the above approach:
['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:
['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.
['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.