I have a list, sometimes it is nested, sometimes it is not. Based whether it is nested, the continuation is different. How do I check if this list is nested? True
or False
should be output.
example:
[1,2,3]
--> False
[[1],[2],[3]]
--> True
Join Stack Overflow to learn, share knowledge, and build your career.
You can use isinstance
and a generator expression combined with any
. This will check for instances of a list
object within your original, outer list.
In [11]: a = [1, 2, 3]
In [12]: b = [[1], [2], [3]]
In [13]: any(isinstance(i, list) for i in a)
Out[13]: False
In [14]: any(isinstance(i, list) for i in b)
Out[14]: True
Note that any
will return True
as soon as it reaches an element that is valid (in this case if the element is a list) so you don't end up iterating over the whole outer list unnecessarily.
dataframe
. The code for doing that is different if it is flat or nested. Flattening a nested list gives me a different structure to the data. I need to maintain the structure. – jason Jun 12 '14 at 9:34