Join Tuples if similar initial element in Python

PythonServer Side ProgrammingProgramming

When it is required to join tuples if they contain a similar initial element, a simple ‘for’ loop and an ‘of’ condition can be used. To store elements to one list, the ‘extend’ method can be used.

Below is the demonstration of the same −

Example

 Live Demo

my_list = [(43, 15), (66, 98), (64, 80), (14, 9), (47, 17)]

print("The list is : ")
print(my_list)

my_result = []
for sub in my_list:
   if my_result and my_result[-1][0] == sub[0]:
      my_result[-1].extend(sub[1:])
   else:
      my_result.append([ele for ele in sub])
my_result = list(map(tuple, my_result))

print("The extracted elements are : " )
print(my_result)

Output

The list is :
[(43, 15), (66, 98), (64, 80), (14, 9), (47, 17)]
The extracted elements are :
[(43, 15), (66, 98), (64, 80), (14, 9), (47, 17)]

Explanation

  • A list of tuple is defined, and is displayed on the console.

  • An empty list is defined.

  • The list of tuple is iterated over, and is checked to see if the initial elements match.

  • If they match, the element is stored in the empty list.

  • Otherwise, it is first converted into tuple, and then to a list, and then stored in the empty lit.

  • This is the output that is displayed on the console.

raja
Published on 17-Apr-2021 13:03:12
Advertisements