I have a list of tuples. Each tuple’s element 0 is a numeric value. I want to find all the tuples with the minimal value in element 0. For example:
l = [(2, 'a'), (1, 'b'), (3, 'c'), (1, 'd'), (4, 'e'), (1, 'f')] l.sort() i = 1 while i < len(l): if l[i - 1][0] != l[i][0]: break i += 1 print(l[:i])
would give me what I want:
[(1, 'b'), (1, 'd'), (1, 'f')]
My question is (could be three different answers): what is the Code Golf/fastest/most Pythonic way to do this?
Advertisement
Answer
Here’s a solution using min
. The time complexity is O(n) and it uses O(1) auxiliary space (i.e. not including the space for the output list).
from operator import itemgetter min_key, _ = min(lst, key=itemgetter(0)) result = [ (k, v) for k, v in lst if k == min_key ]