Open In App

Python | Join tuple elements in a list

Last Updated : 02 May, 2023
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.



Previous Article
Next Article

Similar Reads

Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python - Join Tuples to Integers in Tuple List
Sometimes, while working with Python records, we can have a problem in which we need to concatenate all the elements, in order, to convert elements in tuples in List to integer. This kind of problem can have applications in many domains such as day-day and competitive programming. Let's discuss certain ways in which this task can be performed. Inpu
5 min read
Python Pandas - Difference between INNER JOIN and LEFT SEMI JOIN
In this article, we see the difference between INNER JOIN and LEFT SEMI JOIN. Inner Join An inner join requires two data set columns to be the same to fetch the common row data values or data from the data table. In simple words, and returns a data frame or values with only those rows in the data frame that have common characteristics and behavior
3 min read
PySpark Join Types - Join Two DataFrames
In this article, we are going to see how to join two dataframes in Pyspark using Python. Join is used to combine two or more dataframes based on columns in the dataframe. Syntax: dataframe1.join(dataframe2,dataframe1.column_name == dataframe2.column_name,"type") where, dataframe1 is the first dataframedataframe2 is the second dataframecolumn_name i
13 min read
Outer join Spark dataframe with non-identical join column
In PySpark, data frames are one of the most important data structures used for data processing and manipulation. The outer join operation in PySpark data frames is an important operation to combine data from multiple sources. However, sometimes the join column in the two DataFrames may not be identical, which may result in missing values. In this a
4 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
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
three90RightbarBannerImg