Member-only story
A sort of Pythonic bite
To sort or to sorted(), that is the question
Suppose we have a list, which we want to sort. We can use the sort() method in Python, in order to arrange the elements of the list in a specific order (ascending order by default).
The key point to note about this method is that:
- In-Place sort: The orignal list gets modified. No new list is created.
- No return value: The method return None.
Let’s look at an example to better understand this.
Let’s start with a simple list.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
Here’s what happens when we use sort()
result = numbers.sort()
If we look at our orignal list,
print("Original list after sort():", numbers)
we get:
[1, 1, 2, 3, 4, 5, 6, 9]
Now let’s see what’s inside the result:
print("Result of sort():", result)
we get:
None
Here we observe that:
- After calling
numbers.sort()
, the originalnumbers
list is rearranged in ascending order. - The return value of…