Python Practice › Tuple Programs › Program 17

Join tuples with the same first element

MediumTuple Programs · 17 of 70

Write a Python program to join tuples that start with the same element.

Advertisement
Input
[(3, 6, 7), (7, 8, 4), (7, 3), (3, 0, 5)]
Output
[(3, 6, 7, 0, 5), (7, 8, 4, 3)]

Approach

  1. Group by the first element in a dict, appending the rest of each tuple.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs