Open In App

Python – Concatenate Rear elements in Tuple List

Improve
Improve
Like Article
Like
Save
Share
Report

Given a tuple list where we need to concatenate rear elements.

Input : test_list = [(1, 2, “Gfg”), (“Best”, )] 
Output : Gfg Best 
Explanation : Last elements are joined. 

Input : test_list = [(1, 2, “Gfg”)] 
Output : Gfg 
Explanation : Last elements are joined.

Method #1 : Using list comprehension + join()

In this, we check for last element using “-1”, as index, and perform concatenation using join(), list comprehension is used to iterate each tuple.

Python3




# Python3 code to demonstrate working of
# Concatenate Rear elements in Tuple List
# Using join() + list comprehension
 
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# "-1" is used for access
res = " ".join([sub[-1] for sub in test_list])
 
# printing result
print("The Concatenated result : " + str(res))


Output

The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best',)]
The Concatenated result : Gfg is Best

Time Complexity: O(n), where n is the elements of tuple
Auxiliary Space: O(n), where n is the size of tuple

Method #2 : Using map() + itemgetter() + join()

In this, we perform task of getting last element using itemgetter(-1), and map() is used to get all the last elements, concatenation using join().

Python3




# Python3 code to demonstrate working of
# Concatenate Rear elements in Tuple List
# Using map() + itemgetter() + join()
from operator import itemgetter
 
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# "-1" is used for access
# map() to get all elements
res = " ".join(list(map(itemgetter(-1), test_list)))
 
# printing result
print("The Concatenated result : " + str(res))


Output

The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best',)]
The Concatenated result : Gfg is Best

Time Complexity: O(n), where n is the length of the input list. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

Method#3: Using Recursive method

Sure, here’s a step-by-step approach:

  1. Define a function named concatenate_last_elements which takes two arguments lst and result. By default result is set to an empty string.
  2. Inside the function, use an if condition to check if lst is empty. If it is, then return result.
  3. If lst is not empty, then concatenate the last element of the first tuple in the list to result, followed by a space. The last element of a tuple can be accessed using the index -1.
  4. Recursively call the concatenate_last_elements function with the remaining list lst[1:] and the updated result.
  5. When the recursion ends, return the final value of result.
  6. Initialize a test list test_list containing tuples with various elements.
  7. Print the original list.
  8. Call the concatenate_last_elements function with the test_list as argument and store the returned value in the variable result.
  9. Print the concatenated result by removing any trailing spaces using the strip() method.

Python3




# Python3 code to demonstrate working of
# Concatenate Rear elements in Tuple List
# Using recursive method
def concatenate_last_elements(lst, result=""):
    if not lst:
        return result
    result += lst[0][-1] + " "
    return concatenate_last_elements(lst[1:], result)
 
 
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
result = concatenate_last_elements(test_list)
# printing result
print("The Concatenated result:", result.strip())
#this code contributed by tvsk


Output

The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best',)]
The Concatenated result: Gfg is Best

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#4:Using reduce()

Step-by-Step Approach:

  1. Initialize the list of tuples test_list.
  2. Using reduce() and lambda function, concatenate the last element of each tuple to the accumulator variable x, with a space separator.
  3. The initial value of the accumulator is an empty string “”.
  4. Print the concatenated string.

Python3




from functools import reduce
 
# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using reduce() to concatenate rear elements
res = reduce(lambda x, y: x + " " + y[-1], test_list, "")
 
# printing result
print("The Concatenated result : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best',)]
The Concatenated result :  Gfg is Best

Time Complexity: The reduce() function takes O(N) time, where N is the length of the list.
Inside the lambda function, accessing the last element of each tuple takes constant time.
Therefore, the overall time complexity of the code is O(N).

Auxiliary Space: We are using a single string variable to store the concatenated string, which takes O(N) space, where N is the length of the list.
Therefore, the overall space complexity of the code is O(N).

Method 5:  Using for loop

In this approach, we first initialize the list of tuples. Then, we use a for loop to iterate through each tuple in the list. We concatenate the last element of each tuple to the res variable. Finally, we print the concatenated result.

 Steps by step approach for the code:

  1. Create a list of tuples test_list with 3 tuples: (1, 2, “Gfg”), (4, “is”), and (“Best”, ).
  2. Print the original list using print(“The original list is: ” + str(test_list)).
  3. Initialize an empty string res.
  4. Use a for loop to iterate through each tuple in test_list.
  5. For each tuple, concatenate the last element of the tuple to the res string with a space in between using the += operator.
  6. Print the concatenated result using print(“The Concatenated result : ” + str(res)).

Python3




# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using a for loop to concatenate rear elements
res = ""
for tpl in test_list:
    res += " " + tpl[-1]
 
# printing result
print("The Concatenated result : " + str(res))


Output

The original list is : [(1, 2, 'Gfg'), (4, 'is'), ('Best',)]
The Concatenated result :  Gfg is Best

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list, as we are storing the concatenated string in a variable.

Method #6: Using a generator expression and the str.join() method.

Steps:

Initialize an empty string variable to store the concatenated result.
Use a generator expression inside the str.join() method to extract the last element of each tuple in the given list and join them with a space separator.
Assign the resulting string to the previously initialized variable.
Print the concatenated result.

Python3




# initializing list
test_list = [(1, 2, "Gfg"), (4, "is"), ("Best", )]
 
# printing original list
print("The original list is: " + str(test_list))
 
# using a generator expression and join() to concatenate rear elements
res = ' '.join(tpl[-1] for tpl in test_list)
 
# printing result
print("The Concatenated result: " + res)


Output

The original list is: [(1, 2, 'Gfg'), (4, 'is'), ('Best',)]
The Concatenated result: Gfg is Best

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as we are only using a single string variable to store the concatenated result.



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