πIterable Functions
What can you do with lists?
Now that we've developed some familiarity with lists, let's quickly discuss some functions that can be used with them to change them or to retrieve values from lists!
Append
To add an element to the list, we use the append keyword. It is essential to remember that append is a mutating function β it returns None. Don't use its return value for anything!
What happens when you try to append a list to a list?
As we hopefully expected, [4, 5]
is considered one element and appended to the list as such!
Extend
Contrary to append
, extend accepts an iterable and appends all the elements of that iterable to the list. Extend is also a mutating function and returns None.
What happens when we try to extend the list with something that is not an iterable?
What happens when we try to extend the list with a list that contains more lists?
Did you figure out that one? It's absolutely alright if you didn't! Hopefully this example helped you develop the intuition behind how extend
appends every element of the iterable it passes in. Also important to remember is that the iterable doesn't need to be a list!
Sum
Unlike append
and extend
, which are mutating functions, sum
is our first aggregating function. It accepts a list and a starting value, and returns the sum of all the elements of the list and the starting value.
Note that the starting value is optional.
What happens when the list is made up of different types of elements? For example:
Therefore, we have to be careful using the sum function, lest we run into unexpected errors like the one above!
Any
any
accepts a list of elements and returns True if any of the elements are truth-y (that is, evaluate to true) and False otherwise. For more about truth-y and false-y values, read here.
Keep in mind any
function's behavior with this edge case:
All
all
is the complement to any.
all
accepts a list of elements returns True if every element evaluates to True, and False otherwise.
Keep in mind all
function's behavior with this edge case:
max
max
accepts a list of values, and given this list, returns the maximum value of that list.
Another error to keep in mind is the following:
That is to say, max
cannot be given an empty list.
The min
function works exactly like the max
function, with the same error cases, with the critical difference of course being that it returns the minimum value instead of the maximum one.
Last updated