• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] How to Sort a List of Tuples? – Most Pythonic Way!

How to Sort a List of Tuples? – Most Pythonic Way!

Did you already try to sort a list of tuples? And when you saw the result,
it wasn’t quiet what you expected? Well, this happend to me when I went deeper
into Python and I suppose, it also happend to you, since you are looking for
a solution. This defenitely shows that you are an advanced Python programmer already!

Use Python’s built-in sorted() function or call the method sort() on the list
you want to sort. Both of them have an optional parameter key which accepts a
function. Pass a function here which computes a key-value from each tuple in the list to sort
the tuples by their computed key-values.
Example for sorting a list of tuples by their second entry:

```lst = [(1, 2), (2, 3), (0, 3)]
lst.sort(key=lambda x: x[1])```

## How to Sort a List of Tuples by Any Element or Custom Value?

Let’s first frame our problem in more detail: We have a list of tuples which we want to sort by
their second element or sum of elements or anything else which is not the first element of the list.
The default behavior of both, sort() and sorted(), is taking the first entry of each tuple to
sort the list of tuples. This is what may lead to surprises for beginners.

Suppose, we want to sort a list of items like this one:

```items = [ ("apple", 1.5), ("pear", 2.3), ("egg", 0.5), ("cherry", 0.2),
]```

We could either sort the tuples by their first element which is the name, or by their second element, the item’s price. To achieve this, we could write a custom sort function. But this wouldn’t be very pythonic.
Instead we want to use the built-in functions which Python provides. Therefore we have to options:

1. call sort() on the list (`items.sort()`)
2. use sorted() to sort the list (`sorted_items = sorted(items)`)

The difference between the two options is that the first one sorts the list in place and the second one creates a new list instance and adds the sorted items to this new instance. So in both cases you end up with a sorted list. If you need to preserve the list’s initial state use sorted(), in any other case you should prefer calling sort() directly on the list. In both cases the list will be sorted by Python’s default: Each tuple’s first entry.
To override the default behavior we use the optional parameter key which is provided by both sort() and sorted(). The parameter key expects a function which can compute a value from a tuple. It is very common to use a lambda to override the default behavior. If you are not yet familiar with Python’s lambdas read all the background knowledge in this article.

To sort the list items by the tuples’ second entry we write:

`items.sort(key=lambda x: x[1])`

or if you want to preserve the initial order of the items:

`new_list = sorted(items, key=lambda x: x[1])`

Our key function takes a tuple x and returns it’s second entry, thus, the final ordering of the list
will only take into account each tuple’s second entry.
We could also write:

`items.sort(key=lambda x: sum(x))`

to sort the tuples by the sum of their entries. Of course, this is not applicable for our example, since the entries of our tuples are strings and integers.

Finally, it is also important to be aware of Python’s default behavior for sorting lists of tuples.
It doesn’t make sense to write:

`items.sort(key=lambda x: x[0])`

because this is just what the default behavior does.

To sum it all up, watch this video:

## Conclusion

Python provides everything you need to sort lists of tuples easily without writing custom sorting functions. All you need to do is define the key-function which computes a value for each tuple by which they should be sorted.

https://www.sickgaming.net/blog/2020/07/...honic-way/

 Possibly Related Threads… Thread Author Replies Views Last Post [Tut] How to Create a List of Dictionaries in Python? xSicKxBot 0 25 07-09-2020, 11:37 AM Last Post: xSicKxBot [Tut] Zip With List Output Instead of Tuple | Most Pythonic Way xSicKxBot 0 33 07-08-2020, 05:41 PM Last Post: xSicKxBot [Tut] Create a List of Random Numbers — The Most Pythonic Way xSicKxBot 0 33 07-07-2020, 04:23 PM Last Post: xSicKxBot [Tut] How to Create a Python List of Size n? xSicKxBot 0 33 07-06-2020, 12:09 PM Last Post: xSicKxBot [Tut] Python List max() xSicKxBot 0 32 07-02-2020, 11:01 AM Last Post: xSicKxBot [Tut] Dict to List — How to Convert a Dictionary to a List in Python xSicKxBot 0 32 06-30-2020, 04:53 AM Last Post: xSicKxBot [Tut] The Most Pythonic Way to Remove Multiple Items From a List xSicKxBot 0 35 06-29-2020, 04:37 AM Last Post: xSicKxBot [Tut] The Most Pythonic Way to Compare Two Lists in Python xSicKxBot 0 30 06-28-2020, 04:18 PM Last Post: xSicKxBot [Tut] List Difference | The Most Pythonic Way xSicKxBot 0 30 06-27-2020, 02:51 PM Last Post: xSicKxBot [Tut] The Most Pythonic Way to Check if Two Unordered Lists Are Identical xSicKxBot 0 33 06-26-2020, 01:57 PM Last Post: xSicKxBot

Forum Jump:

 Upcoming Events

 Latest Threads [Tut] PEP 8: Hanging Indentation and Clo... Last Post: xSicKxBot Today 09:51 AM » Replies: 0 » Views: 3 (Indie Deal) Bundles & Sales Round-up Last Post: xSicKxBot Today 09:50 AM » Replies: 0 » Views: 2 Microsoft - New Microsoft Store experien... Last Post: xSicKxBot Today 09:50 AM » Replies: 0 » Views: 1 Fedora - Backup and restore Toolboxes Last Post: xSicKxBot Today 09:49 AM » Replies: 0 » Views: 1 News - Zelda, Mario And Animal Crossing ... Last Post: xSicKxBot Today 09:49 AM » Replies: 0 » Views: 1 News - Today Is Masahiro Sakurai’s 50th ... Last Post: xSicKxBot Today 09:49 AM » Replies: 0 » Views: 1 News - Marvel's Avengers Will Add Spider... Last Post: xSicKxBot Today 09:49 AM » Replies: 0 » Views: 1 mens leather wallet Last Post: Leila Elinor Today 04:05 AM » Replies: 0 » Views: 4 panama hut Last Post: Leila Elinor Today 04:00 AM » Replies: 0 » Views: 3 nike sneakers for men Last Post: Leila Elinor Today 03:48 AM » Replies: 0 » Views: 5