How To Check If a List Is Nested In Python?

Summary: One of the following methods can be used to check if a list is empty :-

  • Method 1: Using isinstance() With any()
  • Method 2: Using isinstance() And len() Methods Within For Loop

Problem: Given a list; how to check if it is nested or not?

Considering that you have a list such that it is nested at times while sometimes it is not nested. Based on whether it is nested or not the continuation of your program flow would be different. For instance, you are feeding the list into a dataframe. The code for doing that is different depending on whether the list is flat or nested. Flattening the nested list yields a different structure to the data. Thus, you need to maintain the structure. So, how would you differentiate and recognize a nested list from a flattened list (non-nested list)?

Example:

[a,b,c] # Output: --> False
[[1,2,3],[4,5,6]] # Output --> True

In this article let us quickly discuss the methods that can be used to check if a given list is nested or not. So, without further delay let us dive into the solutions.

Method 1: Using isinstance() With any()

The easiest solution to our problem is to use the isinstance() method and a generator expression within the any() function. Before diving into the solution, let us understand the usage of the isinstance() and any() methods that will help us to check the list if it is nested or not.

◉ isinstance is a built-in method in Python which returns True when the specified object is an instance of the specified type, otherwise it returns False.

Syntax:

Example:

a = isinstance(25, int)
print(a)

Output:

True

◉ any() is a built-in function that returns True if any element in an iterable is True, otherwise it returns False.

Syntax:

any(iterable)

Example:

li = [0, 10, 100, 1000]
x = any(li) # Returns True because the first item is True
print(x)

Output:

True

Now that we know the usage of each function, let us have a look at the solution to our problem. Please follow the code given below that demonstrates the solution.

Solution

li_1 = [1, 2, 3]  # flat list
li_2 = [[1, 2, 3], [4, 5, 6]]  # nested list
# Testing for nested list
li_1_output = any(isinstance(i, list) for i in li_1)
li_2_output = any(isinstance(i, list) for i in li_2)
# Printing output
print("Is li_1 Nested?", li_1_output)
print("IS li_2 Nested?", li_2_output)

Output:

Is li_1 Nested? False
IS li_2 Nested? True

Explanation

In the above code the any() method allows us to check for each occurrence of the list while the isinstance() method checks if each instance of an element inside the list is a list itself or not. Therefore in the first case, the output is False since Python does not find any occurrence of another list within li_1 while in the second case it finds a couple of lists within the parent list li_2 and it returns True.

Method 2: Using isinstance() And len() Methods Within For Loop

Another work around for our problem is to use a counter variable that counts the number of elements within the list and compare it with the actual length of the list. If the length of the list is equal to the number of elements within the list then it is not a nested list otherwise it is a nested list. Let us have a look at the program given below that demonstrates this concept. (Please follow the comments along with the code for a better understanding.)

li_1 = [1, 2, 3]  # flat list
li_2 = [[1, 2, 3], [4, 5, 6]]  # nested list


# function to evaluate if the list is nested or not
def count(l):
    flag = 0  # counter variable to keep count of the number of elements in the list
    # iterate through the elements of the list
    for item in l:
        # check if the item is a list (iterable) or not
        if isinstance(item, list):
            flag = flag + len(item)
        else:
            flag = flag + 1
    return flag


x = count(li_1)
print("Is li_1 Nested? ", bool(x != len(li_1)))
y = count(li_2)
print("Is li_2 Nested? ", bool(len(li_2) != y))

Output:

Is li_1 Nested?  False
Is li_2 Nested?  True

The NumPythonic Way

Another interesting approach could be to convert the given list into an array using the Numpy library. Further, if you are working with datasets then it is quite possible that you are dealing with arrays instead of lists which makes it even more reasonable to discuss the NumPythonic way of approaching our problem. While dealing with arrays our task becomes extremely easy because all we have to do now is to check if the given array is a one-dimensional array.

#Note: The ndim attribute allows us to find the dimension of an array and the size() method allows us to find the number of elements of an array along a given axis.

Let us have a look at the following program which will help us to understand how easily we can deduce if the given list is nested or not by converting it to an array.

import numpy as np

li_1 = [[1, 2, 3, 4], [5, 6, 7, 8]]
li_2 = [1, 2, 3, 4, 5]
arr_1 = np.array(li_1)
arr_2 = np.array(li_2)
print("Is arr_1 nested? ", bool(arr_1.ndim > 1))
print("Is arr_2 nested? ", bool(arr_2.ndim > 1))

Output:

Is arr_1 nested?  True
Is arr_2 nested?  False

Edit: If you wish to learn NumPy based on puzzle-based learning then you might be fascinated to have a look at this amazing book published by Chris who helps you to learn with the help of puzzles in this book.

Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy

Conclusion

I hope the methods discussed in this article have helped you to learn some very basic yet very important concepts that can be used to verify if a list is nested or not. The major concepts discussed in this article were:

  • Using isinstance() and any() methods to verify if the given list is nested? We also discussed each method in brief before reaching the final solution.
  • Using isinstance() And len() Methods Within For Loop to verify if the given list is nested?
  • Using the numpy library to verify if the given list is nested?

With that we come to the end of this article; please subscribe and stay tuned for more interesting articles!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!