
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Join Tuples if similar initial element in Python
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
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.
- Related Questions & Answers
- Check if element is present in tuple of tuples in Python
- N element incremental tuples in Python
- Find the Maximum of Similar Indices in two list of Tuples in Python
- Remove tuples from list of tuples if greater than n in Python
- Remove similar element rows in tuple Matrix in Python
- Accessing nth element from Python tuples in list
- Python – Test if Rows have Similar frequency
- Filter Tuples by Kth element from List in Python
- Filter tuples according to list element presence in Python
- Find the tuples containing the given element from a list of tuples in Python
- Python – Remove Rows for similar Kth column element
- Checking if starting digits are similar in list in Python
- Python program to Sort Tuples by their Maximum element
- Rear element extraction from list of tuples records in Python
- Check if two list of tuples are identical in Python
Advertisements