List are common data structures in every programing language. Python include many built-in functions to manipulate it (count number of elements, find distinct values, etc…) and this in a functional way (a given input provide a given output, no in-place modification).
Used data for the following example is a common data structure, a list of list:
A flat list of this values can be computed using
list is just used to print the values as an iterator is returned.
From this values it is easy to find distinct values casting the list into a
Now let’s find how many times values are found in the list using
We can see that the value 2 is found four times, the 1 three times and the 4 two times.
function can be used to apply an instruction on an iterable. For example to
format number in string:
Another nice concept is list comprehensions, it allow to create list and iterate over it in a very concise way. Check the official documentation if you are not yet comfortable with it.
Using a list comprehension let’s find if the number
1 is found in each
Some filtering can be done using directly with list comprehension:
The same filtering may also be done using
This examples highlight how powerful functional programing can be and how rich is Python standard library. There is tones of other function that can save lots of time, take some time to explore the documentation it worth it!