Find set with smallest number of elements from a list of sets

Viewed 687

I have a list of sets -

inconsistent_case = [{0, 1, 2, 3, 6, 7}, {4, 5}]

I want -

{4, 5} (set with smallest number of elements)

My code -

length = float("inf")
small = {}
for x in inconsistent_case:
    if len(x) < length:
        length = len(x)
        small = x
print(small)

Which gives me -

{4, 5}

Is there any fastest and/or easiest way to do this?

1 Answers

Yes, specify the key for min:

>>> inconsistent_case = [{0, 1, 2, 3, 6, 7}, {4, 5}]
>>> min(inconsistent_case, key=len)
{4, 5}

If multiple items are minimal, the function returns the first one encountered.

Related