ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Python program to join tuples if similar initial element

Here, we will take user input for a list of tuples and then join the tuples with similar initial elements using Python programming language.
Submitted by Shivang Yadav, on June 08, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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:

# Python program to join tuples if similar initial element

# Creating list of tuples
myList = [(2, 5), (9, 4), (9, 0), (1, 4), (1, 5)]
print("Initially the list is : " + str(myList))

# joining tuples if similar initial element
joinList = []
for val in myList:										
	if joinList and joinList[-1][0] == val[0]:			
		joinList[-1].extend(val[1:])						
	else:
		joinList.append([ele for ele in val])	
joinList = list(map(tuple, joinList))

# Printing the joined List
print("Joined list : " + str(joinList))

Output:

Initially the list is : [(2, 5), (9, 4), (9, 0), (1, 4), (1, 5)]
Joined list : [(2, 5), (9, 4, 0), (1, 4, 5)]

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:

# Python program to join Tuples if similar initial element

from collections import defaultdict

# Creating list of tuples
myList = [(2, 5), (9, 4), (9, 0), (1, 4), (1, 5)]
print("Initially the list is : " + str(myList))

# joining tuples if similar initial element
ddList = defaultdict(list)
for key, val in myList:
	ddList[key].append(val)
joinedList = []
for key, val in ddList.items():
    listVal = ([key] + (val))
    joinedList += tuple(i for i in listVal)

# Printing the list of tuples
print("Joined list : " + str(joinedList))

Output:

Initially the list is : [(2, 5), (9, 4), (9, 0), (1, 4), (1, 5)]
Joined list : [9, 4, 0, 2, 5, 1, 4, 5]

Python Tuple Programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.