Python | Test for nested list - GeeksforGeeks (2024)

Last Updated : 05 Dec, 2023

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

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)



manjeet_04

Python | Test for nested list - GeeksforGeeks (3)

Improve

Previous Article

Nested List Comprehensions in Python

Next Article

Python | How to copy a nested list

Please Login to comment...

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 | 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 - 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 | 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 Python | Remove all duplicates and permutations in nested list Given a nested list, the task is to remove all duplicates and permutations in that nested list. Input: [[-11, 0, 11], [-11, 11, 0], [-11, 0, 11], [-11, 2, -11], [-11, 2, -11], [-11, -11, 2]] Output: {(-11, 0, 11), (-11, -11, 2)} Input: [[-1, 5, 3], [3, 5, 0], [-1, 5, 3], [1, 3, 5], [-1, 3, 5], [5, -1, 3]] Output: {(1, 3, 5), (0, 3, 5), (-1, 3, 5)} 4 min read Python | Find the sublist with maximum value in given nested list Given a list of list, the task is to find sublist with the maximum value in second column. Examples: Input : [['Paras', 90], ['Jain', 32], ['Geeks', 120], ['for', 338], ['Labs', 532]] Output :['Labs', 532] Input: [['Geek', 90], ['For', 32], ['Geeks', 120]] Output: ['Geeks', 120] Below are some tasks to achieve the above task. Method #1: Using lambd 4 min read Python | Remove duplicates from nested list The task of removing duplicates many times in the recent past, but sometimes when we deal with the complex data structure, in those cases we need different techniques to handle this type of problem. Let's discuss certain ways in which this task can be achieved. Method #1 : Using sorted() + set() This particular problem can be solved using the above 5 min read Python | Remove all occurrences in nested list The task of removing an element generally doesn't pose any challenge, but sometimes, we may have a more complex problem than just removing a single element or performing removal in just a normal list. The problem can be removing all occurrences of the nested list. Let's discuss certain ways in which this problem can be solved. Method #1: Using list 5 min read Python | Column wise sum of nested list Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list. Examples: Input : [[1, 5, 3], [2, 7, 8], [4, 6, 9]] Output : [7, 18, 20] Input : [[20, 5], [2, 54], [45, 9], [72, 3]] Output : [139, 71] Method #1: C/C++ Code # Python3 program to Column wise su 3 min read python | Nested List Intersection Matrix Product The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists and return their product. Let’s discuss certain ways in which this operation can be performed. Method #1 : Us 3 min read Python - Value nested grouping on List Sometimes, while working with data, we can have a problem in which we have flat data in the form of a list of dictionaries, and we need to perform the categorization from that bare dictionaries according to ids. This can have applications in domains that involve data, such as web development and Data Science. Let's discuss the certain way in which 6 min read Python - Inner Nested Value List Mean in Dictionary Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using mean() + loop The 5 min read Python - Unnest single Key Nested Dictionary List Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let's discuss certain ways in which this 7 min read Python - Type conversion in Nested and Mixed List While working with Python lists, due to its heterogeneous nature, we can have a problem in which we need to convert the data type of each nested element of list to a particular type. In mixed list, this becomes complex. Let's discuss the certain ways in which this task can be performed. Input : test_list = [('7', ['8', ('5', )])] Output : [(7, [8, 7 min read Python - Convert Dictionaries List to Order Key Nested dictionaries Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output : 6 min read Python - Create Nested Dictionary using given List Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value. Input : test_dict = {'Gfg' : 4, 'best' : 9}, test_list = [8, 2] Output : {8: {'Gfg': 4}, 2: {'best': 9}} Explanation : Index-wise key-value pairing from list [8] to dict {'Gfg' : 4} and so on. Input : test_dict = {'Gfg' : 4}, test 3 min read Python - K list Nested Dictionary Mesh Given 2 lists, create nested mesh with constant List. Input : test_list1 = [4, 6], test_list2 = [2, 7], K = [] Output : {4: {2: [], 7: []}, 6: {2: [], 7: []}} Explanation : Nested dictionary initialized with []. Input : test_list1 = [4], test_list2 = [2], K = [1] Output : {4: {2: [1]}} Explanation : Nested dictionary initialized with [1]. Method : 2 min read Python Program to Find the Total Sum of a Nested List Using Recursion A nested list is given. The task is to print the sum of this list using recursion. A nested list is a list whose elements can also be a list. Examples : Input: [1,2,[3]] Output: 6 Input: [[4,5],[7,8,[20]],100] Output: 144 Input: [[1,2,3],[4,[5,6]],7] Output: 28 Recursion: In recursion, a function calls itself repeatedly. This technique is generally 5 min read How to iterate through a nested List in Python? In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List. Iterating through a Nested List Lets us see how a typical nested list 2 min read Python Program to Flatten a Nested List using Recursion Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l 3 min read Python | How to copy a nested list Copying a nested list in Python involves preserving both the structure and values of the original. One common method is using copy.deepcopy() from the copy module. Additionally, list comprehensions with slicing offer a concise approach for creating an independent duplicate. In the previous article, we have seen how to clone or Copy a list, now let' 4 min read Python | Split nested list into two lists Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Split Nested List into Two ListsBelow are the ways b 5 min read Python - Nested List to single value Tuple Sometimes, while working with Python data, we can have problems in which we need to convert Python Nested lists to single values tuples. This kind of problem can have applications in domains such as web development and competitive programming. Let's discuss certain ways in which this task can be performed. Example: Input : test_list = [[5, 6], [4, 7 min read Python | Convert list of nested dictionary into Pandas dataframe Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th 4 min read

Article Tags :

  • Python
  • Python Programs
  • Python list-programs

Practice Tags :

  • python
Python | Test for nested list - GeeksforGeeks (2024)
Top Articles
What is a payment holiday?
Help with Your Card | Reasons & Solutions Card Won't Work | Emirates NBD
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 6235

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.