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.

4

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

2 Comments

longer and slightly slower Why would it be slower?
@Gabriel Because the builtin-any is written in C (at least if we're talking about CPython), while the loop+if is "only" Python.
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 

Comments

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 

4 Comments

Don't call the list input and type(list()) literally is list.
@Wombatz thanks for the pointer on the redundancy of type(list()), I updated my answer. What's the concern with the use of input on a code example?
It's a built-in function in both python2 and python3
@Wombatz Thanks for your corrections, much appreciated. I'll update the answer again :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.