Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether all elements in a list of lists are strings

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?

like image 507
Cleb Avatar asked Dec 13 '25 23:12

Cleb


1 Answers

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) ):
    ...
like image 58
dani herrera Avatar answered Dec 15 '25 14:12

dani herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!