How to apply a function to each sublist of a list in python?

You can use the builtin map to do this.

So if the function you want to apply is len, you would do:

>>> list_of_lists = [['how to apply'],['a function'],['to each list?']]
>>> map(len, list_of_lists)
[1, 1, 1]

In Python3, the above returns a map iterator, so you will need an explicit list call:

>>> map(len, list_of_lists)
<map object at 0x7f1faf5da208>
>>> list(map(len, list_of_lists))
[1, 1, 1]

If you are looking to write some code for this which has to be compatible in both Python2 and Python3, list comprehensions are the way to go. Something like:

[apply_function(item) for item in list_of_lists]

will work in both Python 2 and 3 without any changes.

However, if your input list_of_lists is huge, using map in Python3 would make more sense because the iterator will be much faster.

Leave a Comment