Lists
Understanding Python's sort() Method¶
Let's start with a surprising example:
numbers = [3, 2, 4, 5, 1]
sorted_numbers = numbers.sort()
# THIS WILL OUTPUT None
print(sorted_numbers) # Output: None
In this example, the output is None. Surprised and expected [1,2,3,4,5]?.
Let's find out what happens in the backend¶
The sort() method sorts a list without creating a new list.
The sort() method sorts the elements of a list in place, meaning it modifies the original list directly without creating a new list. It does not return a new sorted list, but rather updates the existing list and returns None.
This is the key difference between the sort() method and the sorted() function. The sorted() function returns a new list that is sorted, while the sort() method sorts the list it is called on and does not create a new list.
Let's see some examples¶
Example 1: Using sort() method
Example 2: Using sorted() function
numbers = [3, 2, 4, 5, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4, 5]
print(numbers) # Output: [3, 2, 4, 5, 1]