How would I check to see if a list contains other lists? I need it so that
[['cow'], 12, 3, [[4]]]
would output True
, while something like
['cow', 12, 3, 4]
would output False
.
How would I check to see if a list contains other lists? I need it so that
[['cow'], 12, 3, [[4]]]
would output True
, while something like
['cow', 12, 3, 4]
would output False
.
If you also want to find subclasses of lists then you should use isinstance
:
def any_list_in(obj):
return any(isinstance(item, list) for item in obj)
any
stops as soon as the condition is True
so this only needs to check only as many items as necessary.
>>> any_list_in([['cow'], 12, 3, [[4]]])
True
>>> any_list_in(['cow', 12, 3, 4])
False
The isinstance(item, list) for item in obj
is a generator expression that works similar to a for
-loop or a list-comprehension. It could also be written as (longer and slightly slower but maybe that's better to comprehend):
def any_list_in(obj):
for item in obj:
if isinstance(item, list):
return True
return False
Here's a neat solution using a list comprehension.
Given obj = [['cow'], 12, 3, [[4]]]
, we'll first use a list comprehension to get a list of types in obj
:
>>> [type(x) for x in obj]
[<type 'list'>, <type 'int'>, <type 'int'>, <type 'list'>]
Now, we simply check if list
is in the list of types we created. Let's revisit our list comprehension and turn it into a boolean expression:
>>> list in [type(x) for x in obj]
There, that's nice and short. So does it work?
>>> obj = [['cow'], 12, 3, [[4]]]
>>> list in [type(x) for x in obj]
True
>>> obj = ['cow', 12, 3, 4]
>>> list in [type(x) for x in obj]
False
You can use this method if your list does not contain some string with '[' int it .
def check(a):
a=str(a)
if a.count('[')==1: # or a.count(']')==1;
return False
return True
In python 2.7 we have a module for this work:( I don't know about any such module in python 3.x )
from compiler.ast import flatten
def check(a):
if flatten(a)==a:
return False
return True