How To Store A List In A List In Python

In Python, a list is a versatile and powerful data structure, capable of storing multiple values of different data types like integers, strings, and objects.

Sometimes, we may encounter a situation where we need to store a list inside another list. This concept is known as a nested list or multidimensional list. In this tutorial, we will learn how to create and manipulate nested lists in Python.

Step 1: Creating a Nested List

To create a nested list, you simply need to include a list as an element inside another list. Here’s an example of a nested list with three sublists:

In the example above, nested_list has three elements, each of which is a list containing three integers. In other words, nested_list is a 3×3 matrix.

Another way to create a nested list is using list comprehension, like this:

This will result in the same nested list as before.

Step 2: Accessing Elements in a Nested List

To access elements in a nested list, use multiple indexing. The first index will refer to the outer list, and the second index will refer to the inner list. Here’s an example that demonstrates how to access elements in our nested list:

In this example, element will be equal to the value 6, as it is the third element in the second list (remember that Python uses zero-based indexing).

Step 3: Modifying Elements in a Nested List

You can modify elements in a nested list in the same way that you modify elements in a regular list, by using multiple indexing:

After this operation, the nested list will look like this:

Step 4: Iterating Over a Nested List

To iterate over a nested list, you can use a nested loop. The outer loop will iterate over each sublist, and the inner loop will iterate over each element within that sublist. Here’s an example that demonstrates how to iterate over each element in our nested list:

This will print the elements of the nested list, one per line:

1
2
3
4
5
42
7
8
9

Full Code

Here’s the full code for this tutorial:

Conclusion

In this tutorial, we have learned how to create and manipulate nested lists in Python. We’ve covered creating a nested list, accessing elements in a nested list, modifying elements in a nested list, and iterating over a nested list. With this knowledge, you can now work confidently with nested lists in your Python projects.