Python – Concatenate Rear elements in Tuple List

PythonServer Side ProgrammingProgramming

When it is required to concatenate the rear elements in a tuple list, a list comprehension and the ‘join’ methods are used.

Example

Below is a demonstration of the same −

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 list is :
[(13, 42, 'Will'), (48, 'is a'), ('good boy',)]
The concatenated list is :
Will is a good boy

Explanation

  • A list of tuple is defined and is displayed on the console.

  • A list comprehension and the ‘join’ method is used to get the last element in the list of tuple.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 08:29:06
Advertisements