Python check if a list is nested or not

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)