Nesting Lists in Python
In Python, you can create nested lists. But what exactly is a nested list? It's a list contained within another list. This is also known as an embedded list.
An Example
[1, 2, 3, ["a", "b", "c"]]
Searching in a Nested List
When searching in a nested list, the search is limited to the elements at the first level; it doesn't perform a deep search.
Example
This list includes a nested list:
lista1 = [1, 2, 3, ["a", "b", "c"]]
If you search for the element "a" using the index function:
lista1.index("a")
the command won't find it because "a" is inside a nested list (second-level list).
However, if you search for:
lista1.index(3)
The search for the element 3 will be successful:
2
The number 3 is in the first-level list. It is the third element (at position 2).
Creating a Matrix with Nested Lists
Nested lists are very useful for creating matrices in Python.
Practical Example
Using list comprehension in Python, you can create an identity matrix.
n = 5
matrix = [[(1 if x == y else 0)
for x in range(n)] for y in range(n)]
This command creates an identity matrix, which is a matrix with ones on the diagonal and zeros elsewhere.
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
The elements of the first-level list represent the rows of the matrix.
The elements of the second-level list (nested list) represent the columns of the matrix.
If you print the list, the final result will be:
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
This is an identity matrix:
[1, 0, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 0, 1, 0]
[0, 0, 0, 0, 1]
That's how you create an identity matrix in Python.