Difference between sorted() and .sort() in Python

Why is the sort() used like my_list.sort() but sorted() is used as sorted(my_list)? What is the key difference between them?

Difference between sorted() and .sort() in Python

Why is the sort() used like my_list.sort() but sorted() is used as sorted(my_list)? What is the key difference between them?

The key differencePermalink

The most significant difference is the following:

sorted() is a function that reads an existing list (passed in as a parameter) and creates a new list with the same values as the original list but sorted. It leaves the original list untouched.

sort() is a method called on a list and modifies that list by ordering its items. It doesn't return anything.

Let's look more closely at each.

sort()Permalink

sort() is a method available only on list objects. It sorts the list we call it on. That means it modifies the list itself.

original = [8, 6, 4, 2]

original.sort()

print(original)
# outputs: [2, 4, 6, 8]

sorted()Permalink

sorted() is a function.

  • It takes any iterable as a parameter, not just a list. That means we can give it a tuple or dictionary etc.
  • It doesn't modify the list (or iterable) we give it. It leaves the original list (iterable) untouched.
  • It creates a new list that contains the same values as the original list (iterable) but ordered. It always returns a list regardless of the iterable we give it.
original = [8, 6, 4, 2]

ordered = sorted(original)

print(ordered)
# outputs: [2, 4, 6, 8]

print(original)
# outputs: [8, 6, 4, 2]

Below are a few samples of how sorted() works with other iterables.

ordered_from_tuple = sorted((4, 3, 2, 1))
print(ordered_from_tuple)

# outputs: [1, 2, 3, 4]

ordered_from_set = sorted({4, 3, 2, 1})
print(ordered_from_tuple)
# outputs: [1, 2, 3, 4]

my_dict = {1: 'a', 2: 'b', 3:'c', 4:'d'}
ordered_from_dict = sorted(my_dict)
print(ordered_from_dict)
# outputs: [1, 2, 3, 4]

As we can see, when we give sorted() a dict, it just takes the keys and returns them ordered in a list. It completely ignores values.

You might also like

Join the newsletter

Subscribe to learn how to become a Remote $100k+ developer. Programming, career & Python tips.