0

How to process tuple in a list?

A list like [(1,a,2),(2,b,3)] is given and I have to process last find the smallest among the last element of the tuples. How can I do this?

30th Dec 2019, 3:31 PM
Kamakshi Trivedi
5 Answers
+ 4
Sorry Honfu, your solution gives an Error: "int object is not callable".
30th Dec 2019, 5:59 PM
Lothar
Lothar - avatar
+ 4
If i understood it correctly, that the smallest 3rd element in tuples should be found: (This not the shortest solution - I know) lst = [(1,'a',2),(2,'b',3),(7,'c',11),(4,'d',2)] min = lst[0][2] for i in lst: if i[2] < min: min = i[2] print(min) # output is 2
30th Dec 2019, 6:23 PM
Lothar
Lothar - avatar
+ 2
min(your_list, key=lambda x: x[2])
30th Dec 2019, 4:43 PM
HonFu
HonFu - avatar
+ 2
Ah, okay, if not the tuple itself, but the number only is supposed to be found, just append a [2] to my min call. Basically we get to the same result walking a different path: You compare the last values directly, I compare the tuples by their last values.
30th Dec 2019, 6:24 PM
HonFu
HonFu - avatar
+ 1
Lothar, I have just ran it to see if I was mistaken, but the code does what it's supposed to do: Find the smallest tuple in a list by the last element. Copypaste this and see for yourself: a =[(4, 3, 2), (5, 7, 1), (3, 3, 3)] print(min(a , key=lambda x: x[2])) Output: (5, 7, 1), because this is the tuple with the smallest last element.
30th Dec 2019, 6:22 PM
HonFu
HonFu - avatar