Python for Data Engineers

sorted(List) vs List.sorted() in Python

Constantin LunguUpdated 1 min read

Photo by Aram Ramazyan on Unsplash

When I was just starting out with Python I found the distinction between a function doing something in place and returning the result instead pretty interesting.

Understanding this distinction is pretty important as a beginner! Since sorting in one of the most important operations we do in programming, let's look at an example involving exactly that.

➡ sorted([a_list]): is a built-in function than returns a new sorted list, without modifying the original
➡ a_list.sort(): sorts the list in place and doesn't return anything

numbers = [2,3,1,4,5,5]

print(sorted(numbers))
# returns a new, sorted list
# [1, 2, 3, 4, 5, 5]

print(numbers)
# the original list was not affected
# [2, 3, 1, 4, 5, 5]

numbers.sort()
# sorts the original list in-place

print(numbers)
# check that the original list is sorted
# [1, 2, 3, 4, 5, 5]