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)
indentationfor 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.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Lists

  1. What is a list
  2. Extracting elements from a list
  3. Removing an element
  4. Adding elements
  5. How to count occurrences in a list
  6. How to search for an element in a list
  7. Sorting a list
  8. Reversing the order of a list
  9. List comprehension
  10. Nesting list
  11. How to convert a tuple into a list