Kodeclik Logo

Our Programs

Learn More

Schedule

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:

countries = ["USA","Japan","Canada"]
print(countries)

The output will be:

['USA', 'Japan', 'Canada']

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:

countries = ["USA", "Washington D.C.", "New York", 
             "Japan","Tokyo", "Canada"]

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

Nested lists in Python

In a nested list, we create lists within lists and this can go on indefinitely. Here is how that might work for our example:

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
print(countries)

The output will be:

[['USA', ['Washington D.C.', 'New York']], 
['Japan', ['Tokyo']], ['Canada']]

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.

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
print(countries[0])
print(countries[0][0])
print(countries[0][1])
print(countries[0][1][0])

The output is:

['USA', ['Washington D.C.', 'New York']]
USA
['Washington D.C.', 'New York']
Washington D.C.

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:

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
print(countries[0][1][2])

The output is:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(countries[0][1][2])
IndexError: list index out of range

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”.

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
countries[0][1].append("San Francisco")
print(countries[0])
print(countries[0][1])
print(countries[0][1][2])

Now you will not get any error and the program will print:

['USA', ['Washington D.C.', 'New York', 'San Francisco']]
['Washington D.C.', 'New York', 'San Francisco']
San Francisco

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:

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
countries.remove("Canada")

The output is:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    countries.remove("Canada")
ValueError: list.remove(x): x not in list

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:

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
countries.remove(["Canada"])
print(countries)

The output is:

[['USA', ['Washington D.C.', 'New York']], ['Japan', ['Tokyo']]]

as expected.

Similarly, let us try to remove “New York” from the list. Now, either of the two statements below will not work:

countries.remove("New York")
countries.remove(["New York"])

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:

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
countries[0][1].remove("New York")

print(countries)

The output now will be:

[['USA', ['Washington D.C.']], ['Japan', ['Tokyo']], ['Canada']]

Finding the length of a Python nested list

You can use the len() function to find the length of a Python nested list:

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
print(len(countries))

The output will be:

3

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.

def recursive_length(l):
  answer = 0
  for x in l:
    if isinstance(x,list):
      answer += recursive_length(x)
    else:
      answer += 1
  return(answer)

countries = [["USA", ["Washington D.C.", "New York"]],
             ["Japan",["Tokyo"]], ["Canada"]]
print(recursive_length(countries))

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:

6

When writing programs like this it is good to test it on extreme cases, such as an empty list:

print(recursive_length([]))

The output is:

0

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.