Python - Subtract K from tuples list

Python - Subtract K from tuples list

Let's go over how to subtract a value k from each element of tuples in a list.

Goal:

Given a list of tuples, subtract the value k from every element of each tuple.

Step-by-step Guide:

1. Setting up the list and value k

# Example list of tuples tuples_list = [(10, 20), (30, 40), (50, 60)] # Value to subtract k = 5 

2. Using a Loop

The most basic approach is to use a for loop:

new_list = [] for tup in tuples_list: new_tuple = tuple(i - k for i in tup) new_list.append(new_tuple) print(new_list) 

3. Using List Comprehension

A more Pythonic way is using list comprehension:

new_list = [tuple(i - k for i in tup) for tup in tuples_list] print(new_list) 

Both methods will give the result:

[(5, 15), (25, 35), (45, 55)] 

4. Handling Nested Tuples

If your list contains nested tuples and you want to subtract k from every element irrespective of the depth of nesting, you'll need a recursive approach:

def subtract_from_tuple(t, k): return tuple(subtract_from_tuple(i, k) if isinstance(i, tuple) else i - k for i in t) tuples_list = [(10, (20, 30)), (40, (50, 60))] new_list = [subtract_from_tuple(tup, k) for tup in tuples_list] print(new_list) 

For the nested example, the output will be:

[(5, (15, 25)), (35, (45, 55))] 

Recap:

This tutorial walked you through subtracting a value from each element of tuples in a list, with an added segment for handling nested tuples. Using list comprehensions makes the code shorter and more readable, but understanding the loop-based approach is also beneficial.


More Tags

sweetalert2 powershell-5.0 rebase user-interaction flutter-dependencies mapping partition checkstyle gunicorn droppable

More Programming Guides

Other Guides

More Programming Examples