Python | Test for nested list

Sometimes, while working with Python list, we might have a problem in which we need to find that a list is a Matrix or a list contains list as it’s element. This problem can come in Data Science domain as it involves use of Matrices more than often. Let’s discuss certain way in which this task can be performed.

Method : Using any() + isinstance()
The combination of above functions can be used to perform this task. The any() is used to check for each of the occurrence and isinstance() is used to check for list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Test for nested list
# using any() + isinstance()
  
# initialize list
test_list = [[5, 6], 6, [7], 8, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Test for nested list
# using any() + isinstance()
res = any(isinstance(sub, list) for sub in test_list)
  
# printing result
print("Does list contain nested list ? : " + str(res))

chevron_right


Output :

The original list is : [[5, 6], 6, [7], 8, 10]
Does list contain nested list ? : True


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.