Ramy
Ramy

Reputation: 21261

determine if a list contains other lists

if I have a list, is there any way to check if it contains any other lists?

what i mean to say is, I want to know if a list has this strcuture: [] as opposed to this structure [[]]

so, compare [1,2,3,4] to [1,[2,3],4]

this is complicated by the fact that i have a list of strings.

well, phihag's solution seems to be working so far, but what I'm doing is this:

uniqueCrossTabs = list(itertools.chain.from_iterable(uniqueCrossTabs))

in order to flatten a list if it has other lists in it. But since my list contains strings, if this is done on an already flattened list, I get a list of each character of each string that was in the original list. This is not the behavior i was looking for. so, checking to see if the list needs to be flattened before flattening is neccessary.

Upvotes: 32

Views: 31623

Answers (3)

Nate
Nate

Reputation: 12849

You can take phihag's answer even further if you actually want a list of all the lists inside the list:

output_list = filter( lambda x: isinstance(x,list), input_list)

Upvotes: 5

phihag
phihag

Reputation: 288300

any(isinstance(el, list) for el in input_list)

Upvotes: 134

phynfo
phynfo

Reputation: 4938

lst1 in lst2

Yields True iff lst1 is in lst2.

Upvotes: -5

Related Questions