Open In App

Python | Merge Tuple String List values to String

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using list comprehension + join() 

The combination of above functionalities can be used to achieve the solution of above task. In this, we get the character list using list comprehension and conversion task is performed by join(). 

Python3




# Python3 code to demonstrate working of
# Merge Tuple String List values to String
# using list comprehension + join()
 
# initialize list
test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Merge Tuple String List values to String
# using list comprehension + join()
res = [''.join(i) for i, j in test_list]
 
# printing result
print("The joined character list tuple element to string is : " + str(res))


Output : 

The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)] The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]

Time complexity: O(n * m), where n is the length of the input list and m is the maximum length of any tuple in the list.
Auxiliary Space: O(n *m), as the new list created by the list comprehension has the same length and maximum element size as the input list.

Method #2: Using map() + join() + lambda The task performed by list comprehension in the above method can be performed by map() and lambda function can be used to construct the logic to achieve the solution to this task. 

Python3




# Python3 code to demonstrate working of
# Merge Tuple String List values to String
# using map() + join() + lambda
 
# initialize list
test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Merge Tuple String List values to String
# using map() + join() + lambda
res = list(map(lambda sub: "".join(sub[0]), test_list))
 
# printing result
print("The joined character list tuple element to string is : " + str(res))


Output : 

The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)] The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]

The time complexity of this code is O(n), where n is the length of the input list test_list.

The space complexity of this code is O(n), where n is the length of the input list test_list. 

Method #3: Using a for loop

Iterates over each tuple in test_list, joins its first element (a list of strings), and appends the resulting string to the res list. Finally, it prints the result.

Python3




test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
res = []
 
for sub in test_list:
    res.append(''.join(sub[0]))
 
print("The joined character list tuple element to string is : " + str(res))


Output

The joined character list tuple element to string is : ['gfg', 'is', 'best']

The time complexity of this code is O(n*m), where n is the length of the test_list and m is the maximum length of the sub-lists in test_list.
The space complexity of this code is also O(nm), because it creates a new list res to store the concatenated strings. 

Method 4: Using a generator expression

We can also solve this problem using a generator expression, which is similar to a list comprehension but doesn’t create a list in memory. This can be more memory-efficient for large input lists.

Follow the below steps to implement the above idea:

  • Defining a list called test_list. This list contains three tuple elements, where each tuple contains a list of strings and an integer value.
  • Create a generator expression using a for loop that iterates over each tuple element in test_list. Inside the for loop, use the join() method to concatenate all the strings in the current list element of the tuple.
  • Assign this generator expression to a variable called res. The generator expression returns an iterable that yields the concatenated strings for each tuple in test_list.
  • Finally, print the result by converting the generator expression to a list using the list() function and then converting it to a string. Concatenate the string with a message that explains what the program does.

Python3




test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
 
res = (''.join(i) for i, j in test_list)
 
print("The joined character list tuple element to string is : " + str(list(res)))


Output

The joined character list tuple element to string is : ['gfg', 'is', 'best']

Time Complexity: O(n*m).where n is the number of tuples in test_list and m is the maximum length of the string list in each tuple.
Auxiliary Space: O(n*m).where n is the number of tuples in test_list and m is the maximum length of the string list in each tuple.

Method 5: Using reduce() function

  1. Import the reduce() function from the functools module.
  2. Initialize the input list with tuples containing string lists and integer values.
  3. Define a lambda function to concatenate the string lists in each tuple.
  4. Use the reduce() function with the lambda function to apply the concatenation operation on each tuple and return a new list containing the concatenated string values.

Python3




from functools import reduce
 
# initialize list
test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Merge Tuple String List values to String using reduce() function
res = reduce(lambda x, y: x + [''.join(y[0])], test_list, [])
 
# printing result
print("The joined character list tuple element to string is : " + str(res))


Output

The original list : [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
The joined character list tuple element to string is : ['gfg', 'is', 'best']

Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), where n is the number of tuples in the input list.

Method 6: Using a nested for loop and join()

Step-by-step approach :

  • Initializing an empty list res to store our results.
  • Loop over each tuple in the test_list using a for a loop.
    • Initialize an empty string.
    • Loop over each character in the first element of the tuple (tup[0]) using another for loop.
      • For each character, append it to the string.
    • Once we have looped over all characters in the tuple, we append the string to our result list res.
  • Finally, we print the result list.

Python3




test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
 
res = []
for tup in test_list:
    string = ""
    for char in tup[0]:
        string += char
    res.append(string)
 
print("The joined character list tuple element to string is : " + str(res))


Output

The joined character list tuple element to string is : ['gfg', 'is', 'best']

Time complexity: O(n^2) where n is the length of the input list test_list. 
Auxiliary space: O(n), as we create a new list res to store our results, which can be of size n at most.



Similar Reads

Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
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. L
6 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Practice Tags :
three90RightbarBannerImg