Python Group tuples in list with same first value

PythonServer Side ProgrammingProgramming

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:
      # adding the tuple
      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.

raja
Published on 06-Jul-2020 09:41:43
Advertisements