Lesson 11: sort() method
It is quite straightforward to apply a simple .sort() method however there can also be more advanced applications which we will see in the upcoming levels.
Normally, just type your lists variable name and add .sort() to it and your list will be sorted. Let’s see an example.
Function 1: .sort()
.sort() method is very useful and practical list method. It will sort the objects inside a list.
1) .sort() is a method and it’s correct application is calling it on a list such as list.sort()
1) .sort() method will change your list’s order. When you call .sort() method on a list your original list will be changed so if you’d like to preserve the original order either make a copy of your list or use another sorting function that won’t change your data (see: sorted() function).
>>> money_earned = [550, 750, 400, 1200]
[400, 550, 750, 1200]
Note that the actual list itself changed and became a sorted version of itself. In later lessons we will see a useful function that can overcome situation to avoid confusion named: sorted()
Let’s see another example this time with strings and text instead of numbers.
>>> yard_animals = [“goose”, “porcupine”, “ground hog”]
[“goose”, “ground hog”, “porcupine”]
1- You can also sort your list in a reverse order. For this, you can add a parameter inside your sort method parenthesis as: .sort(reverse=True)
Methods and functions can take single or multiple parameters. When they take multiple parameters these are separated with commas. We will see these examples in the upcoming lessons.
Let’s see an example with a list being sorted in reverse order by using .sort() method.
>>> next_trips = [“Japan”, “Belarus”, “Tanzania”]
[“Tanzania”, “Japan”, “Belarus”]
In this example, you can see that the list is reverse sorted based on the first alphabetic orders. If two strings start with the same letter then program will look at the second letters and so on.
Advanced Concepts (Optional)
1- .sort() method can also specify sorting criteria using a parameter called: “key”.
As this concept is slightly more complex it will be explained in the intermediate lessons with the sorted() function.
Besides that, .sort() method and sorted() function work in the same way except .sort() changes the actual list and sorted() doesn’t.
.pop () function
Calm by Claude Joseph Vernet