Program to join the tuple with similar initial elements using Python

Introduction

In this section of python programming, our task is to perform the concatenation of tuple elements having same initials.

Program to join the tuple with similar initial elements using Python

Program

Approach 1

from collections import defaultdict


ip_list = [(1, 8), (1, 9), (1, 71), (2, 3)]
print("The given list is : "+str(ip_list))


# Using loop
output = []
for ele in ip_list:
    if output and output[-1][0] == ele[0]:
        output[-1].extend(ele[1:])
    else:
        output.append([ele for ele in ele])
output = list(map(tuple, output))


print("The output tuple is: "+str(output))

Output

Program to join the tuple with similar initial elements using Python Output 1

Approach 2

from collections import defaultdict


ip_list = [(71, 3), (7, 17), (71, 8), (7, 3), (8, 1)]
print("The given list is : "+str(ip_list))


# Using defaultdict() + loop
map_ele = defaultdict(list)
for i, ele in ip_list:
    map_ele[i].append(ele)
output = [(i, *ele) for i, ele in map_ele.items()]


print("The output tuple is: "+str(output))

Output

Program to join the tuple with similar initial elements using Python Output 2

Explanation

In approach 1, we have used loop and slicing of elements. The elements are traversed and if the elements found is not similar to the previously traversed elements, it is appended to the new tuple. Using slicing, the left elements are added to the new tuple.

From the output of first approach we can observe that only the similar consecutive numbers are joined. This issue is fixed in our second approach where we have used defaultdict(). The defaultdict is same as dictionary in python.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.