How To Sort A Python List?

Use `my_list.sort()` to sort the list in place

Use `sorted(my_list)` to return a new sorted list

Use `my_list.sort(reverse=True)` to sort in descending order

Use `sorted(my_list, reverse=True)` to get a new list in descending order

Use `my_list.sort(key=…)` to sort with a custom key

Use `sorted(my_list, key=…)` to sort with a custom key and return a new list

Use `my_list.sort(key=str.lower)` to sort strings case-insensitively

Use `my_list.sort(key=len)` to sort by length

Use `my_list.sort(key=lambda x: x[1])` to sort by a custom lambda key

Suggested for You

Trending Today