
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Subtract Tuple of Tuples from a Tuple in Python
What is Python Tuple?
A tuple in Python is an ordered collection of items that cannot be changed once, making it immutable. A tuple allows duplicate values and can hold elements of different data types, such as strings, numbers, other tuples, and more. This makes tuples useful for grouping related data while determining that the content remains fixed and unchanged.
Subtracting Tuples from Tuples in Python
To subtract a tuple of tuples from a tuple in Python, we can use a loop or comprehension to filter out elements. Since tuples are immutable and don't support direct subtraction, convert the main tuple to a list and exclude items found in the nested tuples. Then we need to convert the result back to a tuple if needed.
Example
This code defines original as a tuple of numbers. to_remove method contains tuples of elements to exclude. The set specifies to_remove into remove_items. The final tuple determines filters and prints the result.
original = (2, 3, 4, 5, 1) to_remove = ((1, 2), (4,)) remove_items = set(item for sub in to_remove for item in sub) result = tuple(x for x in original if x not in remove_items) print(result)
The result is obtained as follows -
(3, 5)
The direct way to subtract a tuple of tuples from a tuple in Python is to use loops directly. For instance, if we have a tuple of tuples, we can iterate through them to remove specific elements.
Example: Modifying Tuple Elements
Here, we define my_tuple as a collection of tuples, each containing three numbers. The sub tuple determines values to subtract. A nested comprehension iterates through my_tuple, subtracting specified sub[i] values. The output is a new tuple with modified elements.
my_tuple = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14)) sub = (1, 2, 3, 4, 5) result = tuple(tuple(x - sub[i] for x in my_tuple[i]) for i in range(len(my_tuple))) print(result)
The result is generated as follows -
((-1, 0, 1), (1, 2, 3), (3, 4, 5), (5, 6, 7), (7, 8, 9))