{"id":12148,"date":"2023-10-29T00:07:28","date_gmt":"2023-10-28T18:37:28","guid":{"rendered":"https:\/\/techbeamers.com\/?p=12148"},"modified":"2025-11-30T10:52:36","modified_gmt":"2025-11-30T15:52:36","slug":"python-nested-lists","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/python-nested-lists\/","title":{"rendered":"Python Nested List"},"content":{"rendered":"\n<p>In Python, a nested list is a list that contains other lists as its elements. This concept allows you to create more complex data structures, like tables or matrices. Nested lists can be used in programs to represent 2D arrays, tables, and other multi-dimensional data.<\/p>\n\n\n\n<p>The concept of nested lists, where a list can contain other lists, naturally evolved as Python developers needed to represent and manipulate multi-dimensional data.<\/p>\n\n\n\n<p>In this tutorial, we&#8217;ll explore how to create nested lists, use them, and provide some examples to help you understand the concept easily.<\/p>\n\n\n\n<p>Try Yourself:&nbsp;<a href=\"https:\/\/techbeamers.com\/python-programming-questions-list-tuple-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\">The Best 30 Questions on Python List, Tuple, and Dictionary<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-introduction-to-nested-lists\">Introduction to Nested Lists<\/h2>\n\n\n\n<p>A nested list is a list that can <a href=\"https:\/\/techbeamers.com\/program-python-list-contains-elements\/\" target=\"_blank\" rel=\"noopener\">contain other lists as its elements<\/a>. This nesting can go to any depth, meaning you can have lists within lists within lists, and so on. Nested lists are versatile and represent various data structures, such as grids, matrices, and hierarchical data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-create-nested-lists\">Create Nested Lists<\/h3>\n\n\n\n<p>Creating a nested list in Python is straightforward. You can define a list and include other lists as its elements. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = &#91;&#91;'apple', 'banana', 'cherry'], &#91;7, 11, 17], &#91;'dog', 'cat', 'fish']]<\/code><\/pre>\n\n\n\n<p>In this example, the data contains three sublists, each of which contains a mix of strings and numbers.<\/p>\n\n\n\n<p>Must Read: <a href=\"https:\/\/techbeamers.com\/python-list-slicing\/\" target=\"_blank\" rel=\"noreferrer noopener\">Your Ultimate Guide to Python List Slicing<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-accesse-elements-in-nested-lists\">Accesse Elements in Nested Lists<\/h3>\n\n\n\n<p>To access elements in a nested list, you do it via indexing in your Python code. Each level of nesting requires a set of square brackets to access the elements.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = &#91;&#91;'apple', 'banana', 'cherry'], &#91;7, 11, 17], &#91;'dog', 'cat', 'fish']]\n\n# Accessing the second element in the first sublist\nelement = data&#91;0]&#91;1]\nprint(element)  # Output: 'banana'<\/code><\/pre>\n\n\n\n<p>The first set of brackets (<code>[0]<\/code>) accesses the first sublist, and the second set (<code>[1]<\/code>) accesses the second element within that sublist.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-modify-nested-lists\">Modify Nested Lists<\/h3>\n\n\n\n<p>You can modify elements in a nested list just like you would with a regular list. Use indexing to access the element you want to change and then assign a new value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = &#91;&#91;'apple', 'banana', 'cherry'], &#91;7, 11, 17], &#91;'dog', 'cat', 'fish']]\n\n# Changing the value at the first row, second column\ndata&#91;0]&#91;1] = 'kiwi'\nprint(data)\n# Output: &#91;&#91;'apple', 'kiwi', 'cherry'], &#91;7, 11, 17], &#91;'dog', 'cat', 'fish']]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-iterate-through-nested-lists\">Iterate Through Nested Lists<\/h3>\n\n\n\n<p>You can use a <a href=\"https:\/\/techbeamers.com\/python-for-loop\/\" target=\"_blank\" rel=\"noopener\">Python for loop<\/a> to iterate through the elements of a nested list. Here&#8217;s an <a href=\"https:\/\/techbeamers.com\/python-for-loop-example\/\" target=\"_blank\" rel=\"noopener\">example using a nested for loop:<\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = &#91;&#91;'apple', 'banana', 'cherry'], &#91;7, 11, 17], &#91;'dog', 'cat', 'fish']]\n\nfor n in data:\n    for ix in n:\n        print(ix)<\/code><\/pre>\n\n\n\n<p>This code will print all the elements in the <code>data<\/code> list, including both strings and numbers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-common-use-cases\">Common Use Cases<\/h3>\n\n\n\n<p>Nested lists are used in various scenarios, such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Representing grids and matrices.<\/li>\n\n\n\n<li>Storing tabular data where each row is a sublist and each column is an element within that sublist.<\/li>\n\n\n\n<li>Hierarchical data structures, like trees or organizational charts.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-nested-lists-examples-in-python\">Nested Lists Examples in Python<\/h3>\n\n\n\n<p>Here&#8217;s a list of the best 5 Python nested list problems along with their descriptions and example code to help you understand and solve them:<\/p>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-i-linearize-a-nested-list\">i) Linearize a Nested List<\/h4>\n\n\n\n<p><strong>Problem<\/strong>: You have a deep nested list of items, including strings and sublists. Your task is to turn this intricate structure into one list that includes all the elements in the nested list. This process effectively linearizes the nested structure into a single list.<\/p>\n\n\n\n<p><strong>Python code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def linearize(nested):\n    linear = &#91;]\n    for ix in nested:\n        if isinstance(ix, list):\n            # If the item is a list, recursively call the function\n            # to linearize it further and extend the linear list.\n            linear.extend(linearize(ix))\n        else:\n            # If the item is not a list, add it directly to the linear list.\n            linear.append(ix)\n    return linear\n\nnested = &#91;'apple', &#91;'banana', 'cherry'], 'grape', &#91;'kiwi', &#91;'lemon', 'orange']]]\nresult = linearize(nested)\nprint(result)\n\n# Result\n# &#91;'apple', 'banana', 'cherry', 'grape', 'kiwi', 'lemon', 'orange']<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-ii-transposing-a-matrix\">ii) Transposing a Matrix<\/h4>\n\n\n\n<p><strong>Problem<\/strong>: Given a matrix (a nested list of lists), write a Python program to transpose it, swapping rows and columns.<\/p>\n\n\n\n<p><strong>Python code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def transpose(mtx):\n    tr = &#91;&#91;mtx&#91;j]&#91;i] for j in range(len(mtx))] for i in range(len(mtx&#91;0]))]\n    return tr\n\nmtx = &#91;&#91;2, 7, 17], &#91;3, 11, 19], &#91;5, 13, 23]]\ntr = transpose(mtx)\n\nfor r in tr:\n    print(r)\n\n# Result\n# &#91;2, 3, 5]\n# &#91;7, 11, 13]\n# &#91;17, 19, 23]<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-iii-finding-the-sum-of-all-elements-in-a-nested-list\">iii) Finding the Sum of All Elements in a Nested List<\/h4>\n\n\n\n<p><strong>Problem<\/strong>: Calculate the sum of all elements in a nested list, which may contain numbers and other lists.<\/p>\n\n\n\n<p><strong>Python code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def sum_nested(nested_list):\n    total = 0\n    for ix in nested_list:\n        if isinstance(ix, list):\n            total += sum_nested(ix)\n        elif isinstance(ix, int):\n            total += ix\n    return total\n\ndata = &#91;2, 3, &#91;5, 7], &#91;11, &#91;'thirteen', 17]]]\nresult = sum_nested(data)\nprint(result)  # Output: 45<\/code><\/pre>\n\n\n\n<p>Also Check: <a href=\"https:\/\/techbeamers.com\/python-list-all-files-directory\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python List All Files in a Directory<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-iv-finding-the-maximum-value-in-a-nested-list\">iv) Finding the Maximum Value in a Nested List<\/h4>\n\n\n\n<p><strong>Problem<\/strong>: Find the maximum value within a nested list using Python containing numbers and other lists.<\/p>\n\n\n\n<p><strong>Python code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def find_max_nested(nested_list):\n    max_val = float('-inf')\n    for ix in nested_list:\n        if isinstance(ix, list):\n            max_val = max(max_val, find_max_nested(ix))\n        else:\n            if isinstance(ix, int) and ix &gt; max_val:\n                max_val = ix\n    return max_val\n\ndata = &#91;2, 3, &#91;5, 7], &#91;11, &#91;'thirteen', 17]]]\nresult = find_max_nested(data)\nprint(result)  # Output: 17<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-v-checking-for-the-presence-of-an-element\">v) Checking for the Presence of an Element<\/h4>\n\n\n\n<p><strong>Problem<\/strong>: Determine whether a specific element exists in a nested list.<\/p>\n\n\n\n<p><strong>Python code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def element_exists(nested_list, target):\n    for ix in nested_list:\n        if isinstance(ix, list):\n            if element_exists(ix, target):\n                return True\n        else:\n            if ix == target:\n                return True\n    return False\n\ndata = &#91;1, &#91;2, 'apple'], &#91;3, &#91;4, 'banana', 5]]]\ntarget = 'banana'\nresult = element_exists(data, target)\nprint(result)  # Output: True<\/code><\/pre>\n\n\n\n<p>These are common problems involving nested lists in Python, along with example code solutions. Understanding how to work with nested lists is crucial for dealing with complex data structures and solving various programming challenges.<\/p>\n\n\n\n<p>Check This: <a href=\"https:\/\/techbeamers.com\/python-program-convert-lists-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Program to Convert Lists into a Dictionary<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-a-quick-wrap\">A Quick Wrap<\/h3>\n\n\n\n<p>Nested lists in Python are not limited to a fixed number of dimensions, and you can nest lists as deeply as needed to represent the structure of your data.<\/p>\n\n\n\n<p>Python&#8217;s nested lists provide a flexible way to work with multi-dimensional data. With the knowledge you&#8217;ve gained in this tutorial, you should be well-equipped to create, access, and manipulate nested lists in your Python programs. Whether you&#8217;re working with tables, grids, or any other structured data, nested lists can be a powerful tool in your programming toolkit.<\/p>\n\n\n\n<p>Lastly, our site needs your support to remain free. Share this post on social media (<a href=\"https:\/\/www.facebook.com\/TechBeamersWorld\/\" target=\"_blank\" rel=\"noreferrer noopener\">Facebook<\/a>\/<a href=\"https:\/\/twitter.com\/TechBeamers\" target=\"_blank\" rel=\"noreferrer noopener\">Twitter<\/a>) if you gained some knowledge from this tutorial.<\/p>\n\n\n\n<p><strong>Happy coding,<br>Techbeamers.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Python, a nested list is a list that contains other lists as its elements. This concept allows you to create more complex data structures, like tables or matrices. Nested lists can be used in programs to represent 2D arrays, tables, and other multi-dimensional data. The concept of nested lists, where a list can contain [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12155,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_post_was_ever_published":false},"categories":[92],"tags":[],"class_list":{"0":"post-12148","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python-programming-tutorials"},"jetpack_featured_media_url":"https:\/\/techbeamers.com\/wp-content\/uploads\/2023\/10\/When-And-How-To-Use-Python-Nested-Lists.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/12148","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/comments?post=12148"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/12148\/revisions"}],"predecessor-version":[{"id":23313,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/12148\/revisions\/23313"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/12155"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=12148"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=12148"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=12148"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}