Python – Concatenate Rear elements in Tuple List

When working with tuples in Python, you might need to concatenate the last (rear) elements from each tuple in a list. This can be accomplished using list comprehension with the join() method to create a single concatenated string.

Example

Below is a demonstration of concatenating rear elements from a tuple list ?

my_tuple = [(13, 42, "Will"), (48, "is a"), ("good boy", )]

print("The tuple is : ")
print(my_tuple)

my_result = " ".join([sub[-1] for sub in my_tuple])

print("The result is : ")
print(my_result)

Output

The tuple is : 
[(13, 42, 'Will'), (48, 'is a'), ('good boy',)]
The result is : 
Will is a good boy

How It Works

The solution uses two key components:

  • List Comprehension: [sub[-1] for sub in my_tuple] extracts the last element from each tuple using negative indexing ([-1]).

  • Join Method: " ".join() concatenates all extracted elements with a space separator.

Step-by-Step Breakdown

my_tuple = [(13, 42, "Will"), (48, "is a"), ("good boy", )]

# Step 1: Extract rear elements using list comprehension
rear_elements = [sub[-1] for sub in my_tuple]
print("Rear elements:", rear_elements)

# Step 2: Join them with spaces
result = " ".join(rear_elements)
print("Final result:", result)
Rear elements: ['Will', 'is a', 'good boy']
Final result: Will is a good boy

Alternative Approach

You can also use a different separator or handle mixed data types ?

mixed_tuple = [(1, 2, "Hello"), (3, "World"), (4, 5, "Python")]

# Convert all rear elements to strings
result = "-".join([str(sub[-1]) for sub in mixed_tuple])
print("With dash separator:", result)
With dash separator: Hello-World-Python

Conclusion

Use list comprehension with sub[-1] to extract rear elements from tuples, then apply join() to concatenate them. This approach is efficient and handles variable tuple lengths gracefully.

Updated on: 2026-03-26T01:17:28+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements