Best way to check if an item is present in a list of lists? [duplicate]
You can use itertools.chain.from_iterable
:
>>> from itertools import chain
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
>>> '' in chain.from_iterable(example_list)
True
Just in case if the inner lists are bigger(more than 100 items) then using any
with a generator will be faster than the above example because then the speed penalty of using a Python for-loop is compensated by the fast in
-operation:
>>> any('' in x for x in example_list)
True
Timing comparisons:
>>> example_list = [['aaa']*1000, ['fff', 'gg']*1000, ['gg']*1000]*10000 + [['']*1000]
>>> %timeit '' in chain.from_iterable(example_list)
1 loops, best of 3: 706 ms per loop
>>> %timeit any('' in x for x in example_list)
1 loops, best of 3: 417 ms per loop
# With smaller inner lists for-loop makes `any()` version little slow
>>> example_list = [['aaa'], ['fff', 'gg'], ['gg', 'kk']]*10000 + [['']]
>>> %timeit '' in chain.from_iterable(example_list)
100 loops, best of 3: 2 ms per loop
>>> %timeit any('' in x for x in example_list)
100 loops, best of 3: 2.65 ms per loop
You can do use combination of any, map and chain:
In [19]: example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
In [20]: import operator, itertools
In [21]: any(map(operator.not_, itertools.chain(*example_list)))
Out[21]: True
In [22]: example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['not empty', 'gg']]
In [23]: any(map(operator.not_, itertools.chain(*example_list)))
Out[23]: False