Open In App

Python | Join tuple elements in a list

Improve
Improve
Like Article
Like
Save
Share
Report

Nowadays, data is something that is the backbone of any Machine Learning technique. The data can come in any form and its sometimes required to be extracted out to be processed. This article deals with the issue of extracting information that is present in tuples in list. Let’s discuss certain ways in which this can be performed.

Method #1: Using join() + list comprehension The join function can be used to join each tuple element with each other and list comprehension handles the task of iterating through the tuples. 

Python3




# Python3 code to demonstrate
# joining tuple elements
# using join() + list comprehension
 
# initializing tuple list
test_list = [('geeks', 'for', 'geeks'),
             ('computer', 'science', 'portal')]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using join() + list comprehension
# joining tuple elements
res = [' '.join(tups) for tups in test_list]
 
# printing result
print ("The joined data is : " +  str(res))


Output:

The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)] The joined data is : [‘geeks for geeks’, ‘computer science portal’]

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

Method #2: Using map() + join() The functionality of list comprehension in the above method can also be done using the map function. This reduces the size of the code increasing its readability. 

Python3




# Python3 code to demonstrate
# joining tuple elements
# using join() + map()
 
# initializing tuple list
test_list = [('geeks', 'for', 'geeks'),
             ('computer', 'science', 'portal')]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using join() + map()
# joining tuple elements
res = list(map(" ".join, test_list))
 
# printing result
print ("The joined data is : " +  str(res))


Output:

The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)] The joined data is : [‘geeks for geeks’, ‘computer science portal’]

Time complexity: O(n*m), where n is the length of the input list and m is the length of the longest tuple in the list.
Auxiliary space: O(n*m), as the space required to store the output list is proportional to the size of the input list.

Method #3 : Using for loop and rstrip()

Python3




# Python3 code to demonstrate
# joining tuple elements
 
# initializing tuple list
test_list = [('geeks', 'for', 'geeks'),
            ('computer', 'science', 'portal')]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# joining tuple elements
res=[]
for i in test_list:
    s=""
    for j in i:
        s+=j+" "
    s=s.rstrip()
    res.append(s)
 
# printing result
print ("The joined data is : " + str(res))


Output

The original list is : [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')]
The joined data is : ['geeks for geeks', 'computer science portal']

Time complexity: O(n*m), where n is the length of the input list and m is the length of the longest tuple in the list.
Auxiliary space: O(n*m), as the space required to store the output list is proportional to the size of the input list.

Method #4 : Using reduce()

This approach first uses a list comprehension to iterate through each tuple in test_list. For each tuple, the reduce() function is used to iteratively apply the lambda function to the tuple, concatenating the elements of the tuple to the result. The final result for each tuple is a single string containing the joined elements of the tuple. These results are stored in a list using the list comprehension.

Python3




from functools import reduce
 
# Python3 code to demonstrate
# joining tuple elements
# using reduce() and list comprehension
 
# initializing tuple list
test_list = [('geeks', 'for', 'geeks'),
             ('computer', 'science', 'portal')]
 
# printing original list
print("The original list is:", test_list)
 
# using reduce() and list comprehension
# joining tuple elements
res = [reduce(lambda x, y: x + ' ' + y, tup, '') for tup in test_list]
 
# printing result
print("The joined data is:", res)
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is: [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')]
The joined data is: [' geeks for geeks', ' computer science portal']

Time complexity: O(n), where n is the number of tuples in the list
Auxiliary space: O(n), as it requires a separate result variable for each tuple in the list.

Using a generator expression and join() method:

Approach:

Create a list of tuples named lst containing the tuples (‘geeks’, ‘for’, ‘geeks’) and (‘computer’, ‘science’, ‘portal’).

Create a generator expression using a for loop that iterates over each tuple in the lst list.

Inside the for loop, join the current tuple using the join() method and a space separator, and return the resulting string.

Assign the generator expression to a variable named result.

Call the list() function on the result variable to convert the generator object to a list of joined strings.

Print the resulting list using the print() function.

Python3




lst = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')]
result = (' '.join(tpl) for tpl in lst)
print(list(result))


Output

['geeks for geeks', 'computer science portal']

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary Space: O(1), as we don’t create a new list to store the joined strings but a generator object.

Using numpy:

  1. Import the required module numpy using the import statement.
  2. Define a list of tuples called test_list.
  3. Use the numpy.array() method to convert the list of tuples to a numpy array called arr.
  4. Define an empty list called res.
  5. Loop through the range of the number of rows in the numpy array using the range() function and the .shape[0] attribute of the numpy array.
  6. In each iteration, join the elements of the current row using the .join() method and append the result to the res list.
  7. Print the original list and the joined data list.

Python3




import numpy as np
 
# Original tuple list
test_list = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')]
 
# Joining tuple elements using numpy
arr = np.array(test_list)
res = [" ".join(arr[i]) for i in range(arr.shape[0])]
 
# Print the original list and the joined data
print("The original list is:", test_list)
print("The joined data is:", res)
#This code is contributed by Vinay Pinjala.


Output:

The original list is: [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')]
The joined data is: ['geeks for geeks', 'computer science portal']

Time complexity: O(nm), where n is the number of tuples in the list and m is the number of elements in each tuple.

Auxiliary Space: O(nm), since the list of strings created takes up space in memory.



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads