Kodeclik Blog


Python Nested Lists

Nested lists in Python are lists that contain other lists as elements. Although sounding complex, they are conceptually straightforward to program and work with. Just like you index and retrieve elements of a regular list you can index and access elements of nested lists, some of which can be lists themselves.
Let us explore nested lists with an example. Recall that lists are essentially sequential collections of values in Python, like so:
The output will be:
Now suppose we wish to store, associated with the names of countries, some major cities in each country. Now we cannot quite store them next to the countries because that will destroy the structure you have built. For instance, if you update the countries list like so:
This looks fishy because it makes Washington D.C, New York, and Tokyo look like countries themselves as we have placed them next to other countries. We need some way to denote that these are not countries, and further that they are associated with specific countries. This is where nested lists come in.

How to create a nested list

In a nested list, we create lists within lists and this can go on indefinitely. Here is how that might work for our example:
The output will be:
Note that in this list, there are three elements. Each element is itself a list (hence the overall list is a nested list). Each of the three “element lists” has two elements. The first element is the name of the country. The second element is yet another list giving a list of cities within that country. Thus, USA has two cities given, Japan has one city given and Canada has no cities given (to be consistent, we should have given an empty list to denote this, but you get the idea). The important thing to note is that nested lists do not necessarily follow any predefined format/schema - some elements are lists, some elements are lists containing other lists and so on.

Accessing elements of a Python nested list

You access elements of a nested list just as you access elements of a regular list.
The output is:
The first print statement prints the first element (index: 0) of the countries list. Note that this element is itself a list (i.e., ['USA', ['Washington D.C.', 'New York']]). The second print statement prints the first element of the previous result, hence this prints just “USA” (note without a list, because the first element is just the string “USA”). The third print statement prints the second element of the first element and this is thus a list. Finally, the fourth print statement prints the first element of the second element of the first element (phew!) which is just the string “Washington, D.C.”.
If you try accessing an element that doesn’t exist, you will get the expected error:
The output is:
because there is no element after “New York”.

Updating a Python nested list

You can use regular list operations (like “append”) to modify your nested list. Let us try to fix the error above by adding a new city after “New York”.
Now you will not get any error and the program will print:
as expected.

Removing elements from a Python nested list

Similarly, you can use operations like remove to remove specific elements from a list. Let us try to remove the “Canada” element:
The output is:
Wow - what happened? Python complains that “x not in list”. Why is that? This is because the element “Canada” is truly not in the list. The element you are likely looking for is the list “[“Canada”]”, not the string “Canada”. So let us update the statement as follows:
The output is:
as expected.
Similarly, let us try to remove “New York” from the list. Now, either of the two statements below will not work:
bevause no such elements exist (at the main nested list level). Such elements might exist only within the first element’s second element, so we should update our statement like:
The output now will be:

Finding the length of a Python nested list

You can use the len() function to find the length of a Python nested list:
The output will be:
You might be surprised about why the answer is 3 but note that there are indeed only 3 elements in the list. Some of those elements happen to be lists but in overall there are only 3 elements.
If you would like to flatten the lists inside the list and count the total as 6, we need to write a function to do so. We should probably also account for the case where there could be multiple levels of nesting (not just the levels we have here). Hence, it is good to write a recursive function that drills as deep into the list as necessary.
The function recursive_length() takes a list “l” as input, tests, goes through each value of the list, and keeps a running count of values encountered. If the value is itself a list, it calls recursive_length() recursively on that value. Else it adds 1 to the running count and returns the answer.
The output will be, as expected:
When writing programs like this it is good to test it on extreme cases, such as an empty list:
The output is:
So in summary, nested lists are a helpful tool for organizing information in Python into layers and layers of detail. Once you get over the fact that different elements of the list can have differing levels of resolution, the way nested lists work is very similar to how regular lists work, in terms of accessing elements, updating elements, and removing elements. Nested lists are intuitive and easy to understand because they closely resemble the way we organize data in many real life situations.
For closely related content, checkout our blogpost on how to sort a list of tuples in Python and also how to skip a value in a Python list when iterating on it.
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.