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.
How about
[ F(x) for x in list_of_lists ]
which will iterate over list_of_lists, call F with each sublist as an argument, then generate a list of the results.
If you want to use the sublists as all the arguments to F
you could do it slightly differently as
[ F(*x) for x in list_of_lists ]