Suppose I have a list of list of strings like this:
l=[['a','kl_hg', 'FOO'],['b', 'kl_c', 'po']]
Now I would like to use an if command as follows (in pseudo-code!):
if allElementsOf(l).isString():
#do something
From this question I learned how to check a single variable whether it is a string. For a single list I could therefore do:
dummyL = ['a','kl_hg', 'FOO']
if all(isinstance(s, basestring) for s in dummyL):
#do something
and for my actual list l I could then do:
if all(isinstance(el, basestring) for sl in l for el in sl):
#do something
Is that the way to do it or is there a faster solution since that takes some time for huge lists of lists?
Your approach is right, any flatting list short cut seems slowest. A fastest way may be use itertools:
import itertools
l=[['a','kl_hg', 'FOO'],['b', 'kl_c', 'po']]
if all( isinstance(x, basestring) for x in itertools.chain.from_iterable(l) ):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With