Python Practice › Tuple Programs › Program 17
Join tuples with the same first element
Write a Python program to join tuples that start with the same element.
Input
[(3, 6, 7), (7, 8, 4), (7, 3), (3, 0, 5)]
Output
[(3, 6, 7, 0, 5), (7, 8, 4, 3)]
Approach
- Group by the first element in a dict, appending the rest of each tuple.
Solution
data = [(3, 6, 7), (7, 8, 4), (7, 3), (3, 0, 5)]groups = {}for first, *rest in data: groups.setdefault(first, [first]).extend(rest)print([tuple(v) for v in groups.values()])Output
[(3, 6, 7, 0, 5), (7, 8, 4, 3)]
Line by line
Line 3
first, *rest splits each tuple into its first item and the remaining items.
Line 4
The first time a key appears, its list starts as [first]; later tuples only add their remaining items.
Learn the concept
New to this topic? Read the lesson, then come back.