Join Tuples if similar initial element in Python

When you need to join tuples that have the same initial element, you can use a simple loop to check the first element of each tuple. The extend method helps combine elements from tuples with matching initial values.

Example

Let's see how to join tuples with similar initial elements ?

my_list = [(43, 15), (43, 25), (66, 98), (66, 12), (64, 80)]

print("The list is :")
print(my_list)

my_result = []
for sub in my_list:
    if my_result and my_result[-1][0] == sub[0]:
        my_result[-1].extend(sub[1:])
    else:
        my_result.append([ele for ele in sub])

my_result = list(map(tuple, my_result))

print("The joined tuples are :")
print(my_result)

Output

The list is :
[(43, 15), (43, 25), (66, 98), (66, 12), (64, 80)]
The joined tuples are :
[(43, 15, 25), (66, 98, 12), (64, 80)]

How It Works

  • The algorithm iterates through each tuple in the input list

  • For each tuple, it checks if the result list is not empty and the first element of the last tuple in result matches the current tuple's first element

  • If they match, it extends the last tuple in result with elements from the current tuple (excluding the first element)

  • If they don't match, it adds the current tuple as a new entry in the result list

  • Finally, it converts all lists back to tuples using map(tuple, my_result)

Alternative Approach Using defaultdict

Here's another way to solve the same problem using defaultdict ?

from collections import defaultdict

my_list = [(43, 15), (43, 25), (66, 98), (66, 12), (64, 80)]

print("The list is :")
print(my_list)

grouped = defaultdict(list)
for tup in my_list:
    grouped[tup[0]].extend(tup[1:])

my_result = [(key,) + tuple(values) for key, values in grouped.items()]

print("The joined tuples are :")
print(my_result)

Output

The list is :
[(43, 15), (43, 25), (66, 98), (66, 12), (64, 80)]
The joined tuples are :
[(43, 15, 25), (66, 98, 12), (64, 80)]

Conclusion

Both approaches effectively join tuples with similar initial elements. The first method preserves the original order, while the defaultdict approach is more concise for grouping operations.

Updated on: 2026-03-25T19:18:15+05:30

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements