sort a list of sets by number of elements in python

To sort a list of sets based on the number of elements in each set, you can use the sort method of the list with a lambda function as the key argument:

main.py
my_list = [{'a', 'b'}, {'a', 'b', 'c'}, {'a'}, {'a', 'c'}]
my_list.sort(key=lambda x: len(x))
94 chars
3 lines

This will sort my_list in ascending order based on the number of elements in each set. After running the code, the value of my_list will be:

main.py
[{'a'}, {'a', 'c'}, {'a', 'b'}, {'a', 'b', 'c'}]
49 chars
2 lines

If you want to sort the list in descending order, you can prefix the lambda function with the negation operator:

main.py
my_list.sort(key=lambda x: -len(x))
36 chars
2 lines

This will sort my_list in descending order based on the number of elements in each set. After running the code, the value of my_list will be:

main.py
[{'a', 'b', 'c'}, {'a', 'b'}, {'a', 'c'}, {'a'}]
49 chars
2 lines

gistlibby LogSnag