Computer ScienceChapter 3: Programming Fundamentals
3.2.5 Nested List
Nested List
Explanation level
Introduction
A nested list is a list of lists, where the inner lists (or sub-lists) can further contain lists as elements. Nested lists are quite useful in handling complex data like matrices. The textbook explains that to explore nested lists, we can create a matrix and print it.
In a nested list, every element of the outer list is itself a list. This allows you to represent data that has multiple dimensions, such as a table with rows and columns.
Definition
Nested List is a list that contains other lists as its elements. It is a list of lists, where each inner list can further contain lists.
In simple words: A nested list is a list inside another list. It is like a table or matrix with rows and columns.
Main Idea
- Matrices: A 2D array of numbers.
- Tables: Rows and columns of data.
- Complex data structures: Lists of lists of lists.
The textbook demonstrates how to create a 3x3 matrix using a nested list and how to print it in different ways.
Core Concept
Creating a Nested List A nested list is created by placing lists inside another list, separated by commas.
Example from the book (Fig. 3.8, lines 1–5): ```python matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` This creates a 3x3 matrix where: - The outer list has 3 elements (the three rows). - Each inner list has 3 elements (the three columns).
Printing a Nested List The textbook shows three ways to print a nested list:
Method 1: Directly printing the list (line 6): ```python print(matrix) ``` Output: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`
This prints the entire nested list as a single line. The output clearly distinguishes the multiple lists that exist in the list.
Method 2: Using a for loop (lines 8–9): ```python for i in matrix: print(i) ``` Output: ``` [1, 2, 3] [4, 5, 6] [7, 8, 9] ``` Since the list has only 3 members, the loop executes three times, and in every iteration, a row gets printed. This prints the matrix in the form of rows.
Method 3: Using nested loops (lines 11–13): ```python for row in range(len(matrix)): for col in range(len(matrix)): print(matrix[row][col], end=' ') ``` Output: `1 2 3 4 5 6 7 8 9`
Here, the outer loop index is `row` and the inner loop index is `col`. For the first row, all columns are printed, then the same is processed for the second and third rows, and the whole matrix gets printed in a single line.
Accessing Elements in a Nested List Elements in a nested list are accessed using two indexes: the first for the row, the second for the column.
Example: ```python print(matrix[0][0]) # Output: 1 (first row, first column) print(matrix[1][2]) # Output: 6 (second row, third column) print(matrix[2][1]) # Output: 8 (third row, second column) ```
Transpose of a Matrix The textbook extends the program to calculate the transpose of a matrix. The transpose of a matrix swaps its rows and columns — the element at row `i` and column `j` moves to row `j` and column `i`.
Example from the book (Fig. 3.9): ```python matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
transpose = []
for col in range(len(matrix[0])): newrow = [] for row in range(len(matrix)): newrow.append(matrix[row][col]) transpose.append(new_row)
for row in transpose: print(row) ``` **Output**: ``` [1, 4, 7] [2, 5, 8] [3, 6, 9] ```
- Line 5: The outer loop goes through each column in the original matrix.
- Line 6: A new row (`new_row`) is created for the transpose.
- Line 7: The inner loop iterates through each row of the matrix.
- Line 8: The corresponding column value is appended to `new_row`.
- Line 9: Once the inner loop finishes, the new row is added to `transpose`.
- Lines 11–12: The transposed matrix is printed.
The textbook explains: "On line 16, just like in the last example, we placed a nested loop as we know how to access the nested list contents one-by-one. But, while assigning these values to the transpose matrix the rows should be converted into columns and vice versa. Therefore, note that the indices of the transpose matrix are reversed, which will result in the element at row 1 and column 2 to be placed at column 1 and row 2, which was the desired outcome."
Modifying a Nested List You can modify elements in a nested list using their indexes.
Example: ```python matrix[0][1] = 10 print(matrix) ``` Output: `[[1, 10, 3], [4, 5, 6], [7, 8, 9]]`
- Multi-dimensional: Can represent 2D, 3D, or higher-dimensional data.
- Mutable: Elements can be changed using indexes.
- Flexible: Inner lists can have different lengths (jagged arrays).
- Access by multiple indexes: `list[row][col]`.
Intermediate Level
Nested lists are different from flat lists:
| Feature | Flat List | Nested List |
|---|---|---|
| Structure | Single level | Multiple levels (lists inside lists) |
| Access | One index: `list[i]` | Two or more indexes: `list[i][j]` |
| Use case | Simple sequences | Matrices, tables, complex data |
| Printing | Prints elements in a line | Prints rows and columns |
- Directly: Prints the entire nested structure.
- Row by row: Uses a loop to print each inner list.
- Element by element: Uses nested loops to print each element individually.
The transpose example shows how nested lists can be used to perform operations on matrices. The key insight is that the indexes are reversed: `matrix[row][col]` becomes `transpose[col][row]`.
Important Points
- - Nested List: A list that contains other lists as its elements.
- - Created by placing lists inside a list: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`.
- - Access elements: Use two indexes: `matrix[row][col]`.
- - Printing:
- - Directly: `print(matrix)`.
- - Row by row: `for i in matrix: print(i)`.
- - Element by element: Nested loops.
- - Transpose: Swaps rows and columns. Uses nested loops with reversed indexes.
- - Mutable: Elements can be changed using indexes.
- - Use cases: Matrices, tables, multi-dimensional data.
Remember
- - Nested List = List inside a list.
- - Access: `matrix[row][col]`.
- - Printing:
- - Directly: `print(matrix)`.
- - Row by row: `for i in matrix: print(i)`.
- - Element by element: Nested loops.
- - Transpose: Swap rows and columns.
- - Indexes reversed in transpose: `transpose[col][row] = matrix[row][col]`.
- - Use for matrices and tables.
Common Mistakes
- 1. Using only one index for a nested list — You need two indexes: `matrix[row][col]`.
- 2. Forgetting that inner lists can have different lengths — Nested lists can be jagged (inner lists of different lengths).
- 3. Confusing the order of indexes — The first index is the row, the second is the column.
- 4. Trying to print a nested list as a flat list — Printing directly shows the nested structure, not a flat list.
- 5. Forgetting to initialize a new row in the transpose — Each row of the transpose must be a new list.
- 6. Confusing transpose with other matrix operations — Transpose swaps rows and columns; it does not change the values.
Quick Revision
- - Nested List: A list that contains other lists as its elements. It is a list of lists.
- - Creating a nested list: Place lists inside another list: `matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]`.
- - Accessing elements: Use two indexes: `matrix[row][col]`.
- - Printing a nested list:
- - Directly: `print(matrix)`.
- - Row by row: `for i in matrix: print(i)`.
- - Element by element: Nested loops.
- - Transpose of a matrix: Swaps rows and columns. The element at row `i` and column `j` moves to row `j` and column `i`.
- - Example:
- ```python
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- transpose = []
- for col in range(len(matrix[0])):
- newrow = []
- for row in range(len(matrix)):
- new_row.append(matrix[row][col])
- transpose.append(new_row)
- for row in transpose:
- print(row)
- ```
- - Output:
- ```
- [1, 4, 7]
- [2, 5, 8]
- [3, 6, 9]
- ```
60-Second Revision
- Nested List = List inside a list.
- Access: `matrix[row][col]`.
- Printing:
- Directly: `print(matrix)`.
- Row by row: `for i in matrix: print(i)`.
- Element by element: Nested loops.
- Transpose: Swap rows and columns.
- Indexes reversed: `transpose[col][row] = matrix[row][col]`.
- Warning: Use two indexes for nested lists, not one.
Frequently Asked Questions (FAQs)
Q1. What is a nested list in Python? Answer: A nested list is a list that contains other lists as its elements. It is a list of lists, where each inner list can further contain lists. Nested lists are useful for handling complex data like matrices.
- Q2. How do you create a nested list?
- Answer: A nested list is created by placing lists inside another list, separated by commas. For example:
- ```python
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- ```
Q3. How do you access elements in a nested list? Answer: Elements in a nested list are accessed using two indexes: the first for the row, the second for the column. For example, `matrix[0][0]` returns `1`, `matrix[1][2]` returns `6`.
- Q4. How do you print a nested list row by row?
- Answer: Use a `for` loop:
- ```python
- for i in matrix:
- print(i)
- ```
- This prints each inner list on a separate line.
- Q5. How do you print a nested list element by element?
- Answer: Use nested loops:
- ```python
- for row in range(len(matrix)):
- for col in range(len(matrix)):
- print(matrix[row][col], end=' ')
- ```
- This prints all elements in a single line.
Q6. What is the transpose of a matrix? Answer: The transpose of a matrix swaps its rows and columns. The element at row `i` and column `j` moves to row `j` and column `i`. For example, the transpose of `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` is `[[1, 4, 7], [2, 5, 8], [3, 6, 9]]`.
- Q7. How do you calculate the transpose of a matrix using nested lists?
- Answer: Use nested loops with reversed indexes:
- ```python
- transpose = []
- for col in range(len(matrix[0])):
- newrow = []
- for row in range(len(matrix)):
- new_row.append(matrix[row][col])
- transpose.append(new_row)
- ```
Q8. Why are nested lists useful? Answer: Nested lists are useful for representing multi-dimensional data such as matrices, tables, and complex data structures. They allow you to organize data in rows and columns.
Q9. Can inner lists have different lengths in a nested list? Answer: Yes, inner lists can have different lengths. This is called a jagged array. For example, `[[1, 2], [3, 4, 5], [6]]` is a nested list with inner lists of different lengths.
- Q10. How do you modify an element in a nested list?
- Answer: Use the indexes to assign a new value. For example, `matrix[0][1] = 10` changes the element at row 0, column 1 to 10.
Practice Questions
Short Response Questions (SRQs)
- Define a nested list and explain its use.
- How do you create a nested list? Give an example.
- How do you access elements in a nested list?
- Explain how to print a nested list row by row.
- What is the transpose of a matrix? How is it calculated using nested lists?
Extended Response Questions (ERQs)
- Discuss the concept of nested lists in Python. Why are they useful for representing matrices and tables?
- Explain the different ways to print a nested list (directly, row by row, element by element) with examples.
- Analyze the transpose operation on a matrix. How do nested loops and reversed indexes achieve the transpose?
- You are writing a Python program to store and manipulate a 3x3 matrix. Describe how you would use nested lists to create, access, and modify the matrix.
- Compare and contrast flat lists and nested lists. In what situations would you choose one over the other?
Multiple Choice Questions (MCQs)
- Q1. What is a nested list?
- A. A list with no elements
- B. A list that contains other lists as elements
- C. A list that contains only integers
- D. A list that cannot be modified
- Correct Answer: B
- Explanation: A nested list is a list that contains other lists as its elements.
- Q2. How do you access an element in a nested list?
- A. Using one index: `list[i]`
- B. Using two indexes: `list[i][j]`
- C. Using the `get()` method
- D. Using the `find()` method
- Correct Answer: B
- Explanation: Elements in a nested list are accessed using two indexes: `list[i][j]`.
- Q3. What is the output of the following code?
- ```python
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- print(matrix[1][2])
- ```
- A. 3
- B. 6
- C. 9
- D. 5
- Correct Answer: B
- Explanation: `matrix[1][2]` accesses the element at row 1, column 2, which is `6`.
- Q4. How do you print a nested list row by row?
- A. `print(matrix)`
- B. `for i in matrix: print(i)`
- C. `for i in matrix: for j in i: print(j)`
- D. `print(matrix[0])`
- Correct Answer: B
- Explanation: `for i in matrix: print(i)` prints each inner list on a separate line.
- Q5. What does the transpose of a matrix do?
- A. Adds two matrices
- B. Swaps rows and columns
- C. Multiplies two matrices
- D. Inverts the matrix
- Correct Answer: B
- Explanation: The transpose of a matrix swaps its rows and columns.
- Q6. In the transpose operation, what is the correct assignment?
- A. `transpose[row][col] = matrix[row][col]`
- B. `transpose[col][row] = matrix[row][col]`
- C. `transpose[row][row] = matrix[col][col]`
- D. `transpose[col][col] = matrix[row][row]`
- Correct Answer: B
- Explanation: In the transpose, the element at row `i` and column `j` moves to row `j` and column `i`: `transpose[col][row] = matrix[row][col]`.
- Q7. What is the output of the following code?
- ```python
- matrix = [[1, 2], [3, 4]]
- for row in matrix:
- print(row)
- ```
- A. `[1, 2] [3, 4]`
- B. `1 2 3 4`
- C. `[1, 2]` and `[3, 4]` on separate lines
- D. `1 2` and `3 4` on separate lines
- Correct Answer: C
- Explanation: The loop prints each inner list on a separate line: `[1, 2]` and `[3, 4]`.
- Q8. Can inner lists in a nested list have different lengths?
- A. No, they must all be the same length
- B. Yes, they can have different lengths (jagged array)
- C. Only if the outer list is empty
- D. Only if the inner lists contain integers
- Correct Answer: B
- Explanation: Inner lists can have different lengths; this is called a jagged array.
- Q9. What is the purpose of nested loops in printing a nested list element by element?
- A. To print the list directly
- B. To iterate through rows and columns
- C. To sort the list
- D. To reverse the list
- Correct Answer: B
- Explanation: Nested loops iterate through rows and columns to print each element individually.
- Q10. How do you modify an element in a nested list?
- A. Using `append()`
- B. Using `insert()`
- C. Assigning a new value using indexes: `matrix[row][col] = value`
- D. Using `remove()`
- Correct Answer: C
- Explanation: You modify an element by assigning a new value using its indexes: `matrix[row][col] = value`.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.2.5 Nested List
Sticky Notes · Quick Revision
Key Point 1
- Nested List = List inside a list.
Key Point 2
- Access: `matrix[row][col]`.
Key Point 3
- Printing:
Key Point 4
- Directly: `print(matrix)`.
Key Point 5
- Row by row: `for i in matrix: print(i)`.
Key Point 6
- Element by element: Nested loops.
Key Point 7
- Transpose: Swap rows and columns.
Key Point 8
- Indexes reversed: `transpose[col][row] = matrix[row][col]`.
Key Point 9
- Use for matrices and tables.
Same supplied content as this Notes page (shared canonical source).