How To Sort A List In Python?

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

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

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

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

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

Use `sorted(list, key=…)` to sort with a custom key

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

Use `sorted(list, key=len)` to sort by length

Use `list.sort()` for mutable lists when you want to modify the original

Use `sorted()` when you want to keep the original list unchanged

Suggested for You

Trending Today