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:

>>> l = [[1, 2, 4], [2, 2, 4], [1, 2, 1]]

A flat list of this values can be computed using chain:

>>> from itertools import chain
>>> list(chain.from_iterable(l)))
[1, 2, 4, 2, 2, 4, 1, 2, 1]

Here 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 set

>>> set(chain.from_iterable(l)))
set([1, 2, 4])

Now let’s find how many times values are found in the list using Counter:

>>> from collections import Counter
>>> Counter(chain.from_iterable(d.values()))
Counter({2: 4, 1: 3, 4: 2})

We can see that the value 2 is found four times, the 1 three times and the 4 two times.

The map function can be used to apply an instruction on an iterable. For example to format number in string:

>>> list(map(lambda x: '{:03d}'.format(x), chain.from_iterable(l)))
['001', '002', '004', '002', '002', '004', '001', '002', '001']

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 sublist:

>>> [1 in x for x in l]
[True, False, True]

Some filtering can be done using directly with list comprehension:

>>> [x for x in l if 1 in x]
[[1, 2, 4], [1, 2, 1]]

The same filtering may also be done using filter:

>>> list(filter(lambda x: 1 in x, l))
[[1, 2, 4], [1, 2, 1]]

To finish two other useful small functions are any and all.

>>> any([True, True])
True
>>> any([True, False])
True
>>> any([False, False])
False
>>> all([True, True])
True
>>> all([True, False])
False
>>> all([False, False])
False

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!