Categories
Python Answers

How to sort a Python list by two fields?

Spread the love

Sometimes, we want to sort a Python list by two fields.

In this article, we’ll look at how to sort a Python list by two fields.

How to sort a Python list by two fields?

To sort a Python list by two fields, we can use the sorted function.

For instance, we write

sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))

to call sorted to return the list items sorted by calling it with the key argument set to a lamnda function that has a tuple of values to sort by.

We sort x[1] in descending order since we have a minus sign before the value.

Then we assign the returned sorted list to sorted_list.

Conclusion

To sort a Python list by two fields, we can use the sorted function.

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 *