Categories
Python Answers

How to sort a list by multiple attributes with Python?

Spread the love

Sometimes, we want to sort a list by multiple attributes with Python.

In this article, we’ll look at how to sort a list by multiple attributes with Python.

How to sort a list by multiple attributes with Python?

To sort a list by multiple attributes with Python, we can use the sorted function with the operator.itemgetter method.

For instance, we write:

import operator

l = [[12, 'tall', 'blue', 1], [2, 'short', 'red', 9], [4, 'tall', 'blue', 13]]
s = sorted(l, key=operator.itemgetter(1, 2))
print(s)

We have the l nested list that we want to sort by the 2nd and 3rd items in each nested list.

Then we call sorted with l and the key set to operator.itemgetter called with 1 and 2 to sort l and return the sorted list.

We then assign the returned list to s.

Therefore, s is [[2, 'short', 'red', 9], [12, 'tall', 'blue', 1], [4, 'tall', 'blue', 13]].

Conclusion

To sort a list by multiple attributes with Python, we can use the sorted function with the operator.itemgetter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *