Example:
tuple = ("python", "includehelp", 43, 54.23)
Joining Tuples if Similar initial Elements
In programming, you might encounter situations when the collection has tuples with the same initial elements. And in such a situation we need to join all such tuples into a single one with single initial elements followed by other elements sequentially. This is generally done while data cleaning in data science. Here, we will see a method which can help us perform the task.
We will take user input for the list of tuples. And then create a python program to join tuples with similar initial elements.
Example:
Input:
list = [(1, 4), (3, 1), (1, 2), (4, 2), (3, 5)]
Output:
list = [(1, 4, 2), (3, 1, 5), (4, 2)]
A simple solution to the problem is by iterating over the list and then for each tuple check if there exists the first element of the tuple in another tuple if yes, then we will add it to the previous one using the extend method. Else we will create a new tuple in the list and then at the end of the loop. Print the list of tuples.
Program:
Output:
Method 2:
Another method to solve the problem is by using a special type of collection called default dictionary in python.
defaultdict is a special type of dictionary which handles 'key error' by providing default value for non-existing keys.
We will insert all the values of our list of tuples to the default dictionary with a list as value. And then we will extract each key-value pair and turn it to a tuple for the resulting tuple list.
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer