# Python Group tuples in list with same first value

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

In this tutorial, we are going to write a program that groups all the tuples with the same first element. Let's see an example to understand it clearly.

## Input

[(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]

## Output

[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]

Let's see the steps to solve the problem.

• Initialize the list.
• Initialize an empty dictionary.
• Iterate over the list of tuples.
• Check if the first element of the tuple is present as a key in the dictionary or not.
• If it is present, then append the current tuple values without the first one to the previous values.
• If not present, then initialize the key with the current tuple elements including the first element.
• Print the values of the dict as a list.

## Example

Live Demo

# initializing the list
tuples = [(1, 2, 3), (1, 4, 5), (3, 4, 1), (3, 4, 2)]
# empty dict
result = {}
# iterating over the tuples
for sub_tuple in tuples:
# checking the first element of the tuple in the result
if sub_tuple[0] in result:
# adding the current tuple values without first one
result[sub_tuple[0]] = (*result[sub_tuple[0]], *sub_tuple[1:])
else:
result[sub_tuple[0]] = sub_tuple
# printing the result in list
print(list(result.values()))

## Output

If you run the above code, then you will get the following result.

[(1, 2, 3, 4, 5), (3, 4, 1, 4, 2)]

## Conclusion

You can try to solve the problem in different ways. And if you have any doubts in the tutorial, mention them in the comment section.

Updated on 06-Jul-2020 09:42:23