Open In App

Python | Test for nested list

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Test for Nested List in Python

Below are the ways by which we can test for nested lists:

  • Using any() and instance()
  • Using type() Method
  • Using recursive function

Test for Nested List Using any() and instance()

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

Python3




# 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))


Output

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



Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(1)

Python Test Nested List Using type() method

In this example, the Python code determines if the list test_list contains any nested lists by iterating through its elements and setting the variable res to True if a nested list is found. The final output indicates whether the original list contains a nested list or not.

Python3




# 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
res=False
for i in test_list:
    if type(i) is list:
        res=True
        break
# printing result
print("Does list contain nested list ? : " + str(res))


Output

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



Time Complexity: O(n)
Auxiliary Space: O(1)

Testing for Nested List Using Recursive Function

In this example, the Python function has_nested_list employs recursion to determine whether a given list lst contains any nested lists, including nested tuples and sets. The example usage demonstrates the detection of a nested list within the provided list [[5, 6], 6, [7], 8, 10], resulting in the output True.

Python3




def has_nested_list(lst):
    for elem in lst:
        if isinstance(elem, list):
            return True
        elif isinstance(elem, (tuple, set)):
            # check nested tuples and sets too
            if has_nested_list(list(elem)):
                return True
    return False
 
# Example usage
lst = [[5, 6], 6, [7], 8, 10]
result = has_nested_list(lst)
print(result)  # Output: True


Output

True



Time complexity: O(n)
Space complexity: O(m)
 



Previous Article
Next Article

Similar Reads

Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python - Test for empty Nested Records
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if a particular dictionary has nested records, and all of them is empty, i.e with no key or no value in case of list. This kind of problem is quite common in data domains such as Data Science. Let's discuss certain way in which this task can be perform
6 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Python | Find maximum length sub-list in a nested list
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length). Examples: Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : (['A', 'B', 'C'], 3) Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : ([1, 2, 3, 9, 4], 5) Let's discuss different approaches to solve this prob
3 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read
Python - Convert List to custom overlapping nested list
Given a list, the task is to write a Python program to convert it into a custom overlapping nested list based on element size and overlap step. Examples: Input: test_list = [3, 5, 6, 7, 3, 9, 1, 10], step, size = 2, 4Output: [[3, 5, 6, 7], [6, 7, 3, 9], [3, 9, 1, 10], [1, 10]]Explanation: Rows sliced for size 4, and overcoming started after 2 eleme
3 min read
Python - Create nested list containing values as the count of list items
Given a list, the task is to write a Python program to create a nested list where the values are the count of list items. Examples: Input: [1, 2, 3] Output: [[1], [2, 2], [3, 3, 3]] Input: [4, 5] Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]] Method 1: Using nested list comprehension The list will contain the count of the list items for each element e in
2 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Convert given list into nested list
Sometimes, we come across data that is in string format in a list and it is required to convert it into a list of the list. This kind of problem of converting a list of strings to a nested list is quite common in web development. Let's discuss certain ways in which this can be performed. Convert the Given List into Nested List in PythonBelow are th
5 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Practice Tags :