Nested List in Python: Here is What You Have to Know

Do you want to use a nested list in Python but don’t know where to start? This tutorial will show you how to start using nested lists.

Python, a versatile and beginner-friendly programming language, offers a wide range of data structures to help you organize and manipulate data in your programs effectively and nested lists are one of those.

One very handy type of data structure in Python is the nested list, a concept that can initially seem complex but is incredibly useful once you understand it. In simple words, a nested list is a list that contains other lists. This is also called a list of lists.

In this article, we will take a deep dive into nested lists, exploring what they are, why they are useful, how to work with them, and how they differ from regular lists in Python.

What Is a Nested List in Python?

A nested list is simply a list that contains other lists as its elements. Think of it as one or more lists within a list. This structure allows you to create multi-dimensional data structures, making it easier to represent complex data hierarchies.

Each inner list can contain different types of data, such as integers, strings, or even other lists, providing great flexibility.

To create a nested list in Python, you enclose one or more lists within square brackets, like this:

nested_list = [[8, 9, 10], ['x', 'y', 'z'], [True, False]]

This code defines a variable named nested_list, which is a Python list containing three inner lists. Each inner list in this example, holds different types of data, such as numbers, letters, and boolean values.

Here’s a breakdown of the structure:

  • The first inner list [8, 9, 10] contains three integers: 8, 9, and 10.
  • The second inner list [‘x’, ‘y’, ‘z’] contains three strings: ‘x’, ‘y’, and ‘z’.
  • The third inner list [True, False] contains two boolean values: True and False.

This is an example of a Python nested list. It is made of one or more lists inside a list.

Why Use Nested Lists in Python?

Now that we know what nested lists are, let’s explore why they are important for your Python programs.

Nested lists are particularly useful for organizing data that has a hierarchical or structured nature.

Here are some common use cases:

  • Matrices and Grids: When working with mathematical matrices or representing grids, you can use nested lists to store the data row-wise or column-wise.
  • Data Tables: In data analysis and manipulation, you might encounter datasets with rows and columns. Nested lists allow you to represent this type of data efficiently.
  • Tree Structures: If you need to work with hierarchical data like organizational charts or family trees, nested lists can be a natural choice.
  • Complex Data Structures: Sometimes, you will have data with multiple levels of complexity, such as a list of students in different classes, where each class contains a list of students.

How Do You Get Values From a Python Nested List?

Accessing elements of a nested list in Python requires a combination of square brackets to navigate through the layers of the list.

Let’s break down the process step by step.

Suppose you have the following nested list:

nested_list = [[8, 9, 10], ['x', 'y', 'z'], [True, False]]

To access an element, you start by specifying the index of the outer list:

first_inner_list = nested_list[0]
print(first_inner_list)

[output]
[8, 9, 10]

Now, you have isolated the first inner list [8, 9, 10]. To access an element within this inner list, use another set of square brackets:

element = first_inner_list[1]

In this example, the variable element will contain the value 9.

You can also access elements directly by chaining the square brackets:

element = nested_list[0][1]  # This will also give you the value 9

Remember that Python uses zero-based indexing, so the first element of a list is at index 0, the second at index 1, and so on.

How Do You Store Elements in a Nested List in Python?

To store elements in a nested list, you can use assignment statements. To add an element to an existing inner list, simply reference it using its index and assign a new value:

nested_list[0][1] = 40

After this operation, nested_list will become:

[[8, 40, 10], ['x', 'y', 'z'], [True, False]]

You can also add new inner lists to the nested list by using the append method:

new_inner_list = [100, 200, 300]
nested_list.append(new_inner_list)

This appends the new_inner_list at the end of nested_list. And the result is:

[[8, 40, 10], ['x', 'y', 'z'], [True, False], [100, 200, 300]]

Learn more about the list append() method in the Codefather tutorial about adding items to a list in Python.

How Do You Loop Through a Nested List in Python?

Iterating through a nested list in Python often involves nested loops. You’ll need an outer loop to go through the outer list and an inner loop to navigate through the inner lists.

Let’s see how you can do this.

Suppose you have the following nested list:

nested_list = [[8, 9, 10], ['x', 'y', 'z'], [True, False]]

To loop through all the elements, you can use two nested for loops:

for inner_list in nested_list:
    for item in inner_list:
        print(item)

This code will print each element in the nested list one by one. It starts with 8, 9, 10 then moves on to ‘x’, ‘y’, ‘z’, and finally to True and False.

Here is the output of the code:

8
9
10
x
y
z
True
False

Creating a Nested List Using a List Comprehension

You can also create nested lists using list comprehensions. This can work well with data structures used to solve mathematical problems.

Here is how you would create a matrix using list comprehensions:

matrix = [[i * j for j in range(4)] for i in range(4)]
print(matrix)

In this example, we created a 4×4 matrix where each row is a list containing four numbers.

The result is the following matrix:

[[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9]]

You can see that the nested list we created contains four sublists.

As explained before, you can access individual elements of this nested list using two indices. For example, let’s print the value of the first element in the second sublist:

print(matrix[1][0])

[output]
0

What is The Difference Between a List and a Nested List in Python?

Understanding the distinction between a regular list and a nested list is important for effective programming. The main difference lies in the structure and use cases:

  • Structure: A regular list in Python contains a sequence of elements of any data type, while a nested list contains one or more lists as its elements.
  • Use Cases: Regular lists are suitable for storing one-dimensional data, whereas nested lists are ideal for multi-dimensional data and hierarchical structures.
  • Accessing Elements: Accessing elements in a regular list involves using a single set of square brackets and an index, whereas nested lists require multiple sets of square brackets and indices for deeper nesting.
  • Looping: Looping through a regular list is straightforward with a single for loop, while for nested lists you have to use nested for loops.

Conclusion

In this article, we have studied the concept of nested lists in Python. We have explored what they are, how to access and manipulate their elements, and the key differences between regular lists and nested lists.

As you continue your Python journey, mastering nested lists will empower you to work with more complex data structures and tackle a wide range of programming challenges.

So, embrace the power of nesting and elevate your Python programming skills!

Related article: Learn more about working with nested lists by going through the Codefather tutorial on how to flatten a nested list in Python.

Leave a Comment