Python – Add K to Minimum element in Column Tuple List

Sometimes, while working with Tuple records, we can have a problem in which we need to perform task of adding certain element to max/ min element to each column of Tuple list. This kind of problem can have application in web development domain. Let’s discuss a certain way in which this task can be performed.

Input : test_list = [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)], K = 2
Output : [(4, 5), (3, 4), (4, 4), (4, 6), (3, 4), (4, 5)]

Input : test_list = [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)], K = 3
Output : [(4, 5), (3, 5), (5, 5), (4, 6), (3, 5), (4, 5)]

Method : Using min() + loop
The combination of above functions can be used to solve this problem. In this, we perform the task of extracting min’s for each column using min() and addition of K using logic compiled in loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Add K to Minimum element in Column Tuple List
# Using min() + loop
  
# initializing lists
test_list = [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# Add K to Minimum element in Column Tuple List
# Using min() + loop
a_min = min(a for a, b in test_list)
b_min = min(b for a, b in test_list)
res = []
  
for a, b in test_list:
    if a == a_min and b == b_min:
        res.append((a + K, b + K))
    elif a == a_min :
        res.append((a + K, b))
    elif b == b_min:
        res.append((a, b + K))
    else :
        res.append((a, b))
  
# printing result 
print("Tuple after modification : " + str(res))

chevron_right


Output :

The original list is : [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)]
Tuple after modification : [(4, 5), (3, 7), (7, 7), (4, 6), (3, 7), (4, 5)]

 

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.