More on lists
More list methods
Here are a few more helpful methods that can be called on lists:
Method |
Description |
---|---|
|
Reverses the items of the list, mutating the original list. |
|
Sorts the items of the list, mutating the original list. |
|
Returns the number of occurrences of item in the list. If item is not found, returns 0. |
These are documented in further details in that Python list documentation.
Starting from this list:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We can call reverse()
on it like so - remember, it's a method of lists, so we write it using dot notation:
nums.reverse()
That method mutates the original list, so nums
now holds [10, 9, 8, 7, 6, 5, 4, 3, 2, 1].
Now let's try out sorting, starting from this list:
scores = [9.5, 8.2, 7.3, 10.0, 9.2]
We can call the sort()
method on it like so:
scores.sort()
That mutates the scores
list, so it now holds [7.3, 8.2, 9.2, 9.5, 10.0]. If you wanted that sorted in the other direction, you could call reverse
on it after, or just set the optional argument reverse
.
scores.sort(reverse=True)
List functions
Some of the Python global built-in functions can be called on lists (or any iterable object, like strings). Since these are functions, not methods, we pass the list in as an argument instead of using dot notation to call it after the list name.
Function |
Description |
---|---|
|
Returns a sorted version of the iterable object. Set the |
|
Returns the minimum value in the iterable object. |
|
Returns the maximum value in the iterable object. |
So, if you wanted a sorted version of a list but you didn't want to change the original list, you could call sorted()
instead:
scores = [9.5, 8.2, 7.3, 10.0, 9.2]
scores2 = sorted(scores)
You could also get the minimum and maximum values of that list:
max_score = max(scores)
min_score = min(scores)
These three functions also take additional arguments to customize their behavior further, which you can learn more about in the documentation.
List containment
When processing lists with unknown data, we often want to check if a value is inside a list. We can do that using the in
operator, which evaluates to True
if a value is in a list.
For example:
groceries = ["apples", "bananas"]
if "bananas" in groceries:
print("⚠️ Watch your step!")
if "bleach" in groceries:
print("☣️ Watch what you eat!")