1

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.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • 2
    `['cow'] in lst` is all you need – Moses Koledoye Feb 13 '17 at 01:07
  • Do you need to check for specific inner lists, or check if there are any inner lists at all? – Blckknght Feb 13 '17 at 01:07
  • http://stackoverflow.com/questions/2225038/determine-the-type-of-a-python-object – Neo X Feb 13 '17 at 01:11
  • @WilliamStern Please don't forget to mark an answer as [accepted](http://stackoverflow.com/help/accepted-answer). [It seems you are using the code from my answer already](http://stackoverflow.com/questions/42195831) :) – MSeifert Feb 13 '17 at 02:50

3 Answers3

4

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
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

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
daveruinseverything
  • 4,775
  • 28
  • 40
0

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
Anmol Gautam
  • 949
  • 1
  • 12
  • 27