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
issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.
To find the shape (or dimensions) of a nested list or tuple in Python, iterate over each element in the list or tuple and identify its length with the built-in len() function.
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.
We want to check if elements inside outer-list is an instance of list or not, like @Ffisegydd said we can use a generator expression to build a generator and iterate over it using next(), If any element inside the outer-loop is an instance of list then calling next() on the generator will work otherwise if none of the element inside outer-loops belongs to an instance of list then calling next will raise StopIteration
Best case: If it's a nested loop (we can stop iterating as soon as we see the first instance of list)
Worst case: If it's not a nested loop (We need to iterate over all the elements inside the outerlist)
def is_nested_list(l):
try:
next(x for x in l if isinstance(x,list))
except StopIteration:
return False
return True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With