DEV Community

Cover image for What is the difference between list.sort() and sorted() in Python?
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

22

What is the difference between list.sort() and sorted() in Python?

Python provides two ways to sort a list, the built-in list method list.sort() and the built-in function sorted(). Although both will sort the elements of a list, if used incorrectly they can produce unexpected or undesired results.

Differences and similarities

The primary difference between the two is that list.sort() will sort the list in-place, mutating its indexes and returning None, whereas sorted() will return a new sorted list leaving the original list unchanged. Another difference is that sorted() accepts any iterable while list.sort() is a method of the list class and can only be used with lists.

nums = [2, 3, 1, 5, 6, 4, 0]

print(sorted(nums))   # [0, 1, 2, 3, 4, 5, 6]
print(nums)           # [2, 3, 1, 5, 6, 4, 0]

print(nums.sort())    # None
print(nums)           # [0, 1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Both list.sort() and sorted() have the same key and reverse optional arguments and can be called on each list element prior to making comparisons.

When to use each one

list.sort() should be used whenever mutating the list is intended and retrieving the original order of the elements is not desired. On the other hand, sorted() should be used when the object to be sorted is an iterable (e.g. list, tuple, dictionary, string) and the desired outcome is a sorted list containing all elements.


Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay