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

s = sorted(s, key = operator.itemgetter(1, 2))

to call sorted with list s and the key set to the function returned by operator.itemgetter(1, 2) to get the values with keys 1 and 2 from each entry in s.

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 *