Nested List
Overview
Nested lists are a powerful feature in Python that allow for the creation of lists within lists. This capability is particularly useful for representing complex data structures, such as matrices, and enables multi-dimensional indexing. By using nested lists, you can organize data hierarchically and access elements using multiple indices.
Example of a Nested List
Consider the following example, which demonstrates a simple nested list:
nested = [0]
original = [nested, 1]
original
This code snippet creates a nested list where the first element of the original list is another list, nested. The output of this code is:
[[0], 1]
This indicates that the first item in the original list is a reference to the nested list.
Figures
[Figure 5.1](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/137)
Figure 5.1 A list with its first item referring to a nested list
Figure 5.1 visually represents the example above, showing how the original list contains a reference to the nested list as its first item.
[Figure 5.2](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/137)
Figure 5.2 The first item of the original list is still a nested list, but the nested variable refers to a different list.
Figure 5.2 illustrates a scenario where the nested variable is reassigned to a different list, but the original list still holds a reference to the initial nested list.
[Figure 5.3](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-5/137)
Figure 5.3 A shallow copy doesn’t copy nested lists.
Figure 5.3 demonstrates the concept of shallow copying in Python. When a shallow copy of a list is made, the nested lists within it are not copied. Instead, both the original and the shallow copy point to the same nested lists. This means that changes to the nested lists through either reference will affect the other.
Copying Nested Lists
When working with nested lists, it's important to understand the difference between shallow and deep copies. A shallow copy of a list can be obtained using slicing (x[:]), the + operator (x + []), or the * operator (x * 1). However, these methods do not create copies of the nested lists within the original list. Instead, they create references to the same nested lists.
To create a deep copy, which includes copies of all nested lists, you can use the deepcopy function from the copy module. This ensures that changes to the nested lists in the copied structure do not affect the original lists.
FAQ (Frequently asked questions)
What are nested lists in Python?
How do nested lists allow for data representation?
What does Figure 5.1 in 'The Quick Python Book' illustrate?
How can you create a nested list in Python?
What does the code nested = [0]; original = [nested, 1] represent?