- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove tuples having duplicate first value from given list of tuples in Python
When it is required to remove tuples that have a duplicate first value from a given set of list of tuples, a simple 'for' loop, and the 'add' and 'append' methods can be used.
Below is a demonstration for the same −
Example
my_input = [(45.324, 'Hi Jane, how are you'),(34252.85832, 'Hope you are good'),(45.324, 'You are the best.')] visited_data = set() my_output_list = [] for a, b in my_input: if not a in visited_data: visited_data.add(a) my_output_list.append((a, b)) print("The list of tuple is : ") print(my_input) print("The list of tuple after removing duplicates is :") print(my_output_list)
Output
The list of tuple is : [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good'), (45.324, 'You are the best.')] The list of tuple after removing duplicates is : [(45.324, 'Hi Jane, how are you'), (34252.85832, 'Hope you are good')]
Explanation
- A list of tuple is defined, and is displayed on the console.
- An empty set is created, as well as an empty list.
- The list of tuple is iterated over, and if it is not present in the 'set', it is added to the set, as well as to the list.
- This is the output that is displayed on the console.
Advertisements