- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Replace duplicates in tuple in Python
When it is required to replace the duplicates in a tuple with a different value, a 'set' method and the list comprehension can be used.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Python comes with a datatype known as 'set'. This 'set' contains elements that are unique only. The set is useful in performing operations such as intersection, difference, union and symmetric difference.
Below is a demonstration of the same −
my_tuple_1 = (11, 14, 0, 78, 33, 11, 10, 78, 0) print("The tuple is : ") print(my_tuple_1) my_set = set() my_result = tuple(ele if ele not in my_set and not my_set.add(ele) else 'FILL' for ele in my_tuple_1) print("The tuple after replacing the values is: ") print(my_result)
The tuple is : (11, 14, 0, 78, 33, 11, 10, 78, 0) The tuple after replacing the values is: (11, 14, 0, 78, 33, 'FILL', 10, 'FILL', 'FILL')
- A tuple is defined and is displayed on the console.
- Another empty set is created.
- The tuple is iterated over, and elements are appended to list only if they are not already present in the list.
- If they are present, it is replaced with the value 'FILL'.
- This is now converted to a tuple.
- This is assigned to a value.
- It is displayed on the console.
- Related Articles
- Removing duplicates from tuple in Python
- Python Program to Replace Elements in a Tuple
- C++ program to Replace Nodes with Duplicates in Linked List
- Remove Consecutive Duplicates in Python
- Tuple Division in Python
- Tuple multiplication in Python
- Flatten tuple of List to tuple in Python
- Remove All Adjacent Duplicates In String in Python
- Remove Duplicates from Sorted Array in Python
- Built-in Tuple Functions in Python
- Sort lists in tuple in Python
- Unpacking a Tuple in Python
- Tuple Data Type in Python
- Delete Tuple Elements in Python
- Tuple XOR operation in Python