Nested Lists in Python

Nested Lists in Python Code

In Python, nested lists are lists that contain other lists as elements. They are useful for representing structured data like matrices or grids. Here's an overview of how to create and manipulate nested lists in Python.

Creating Nested Lists

You can create nested lists by including lists within a list:

Python Code

# A 2x3 matrix

matrix = [

[1, 2, 3],

[4, 5, 6]

]

Accessing Elements

To access elements in a nested list, you use multiple indices:

Python Code

print(matrix[0][1]) # Output: 2

print(matrix[1][2]) # Output: 6

Modifying Elements

You can modify elements in a nested list by specifying the indices:

Python Code

matrix[0][1] = 9

print(matrix) # Output: [[1, 9, 3], [4, 5, 6]]

Iterating Through Nested Lists

You can use nested loops to iterate through the elements of a nested list:

Python Code

for row in matrix:

for element in row:

print(element)

List Comprehensions with Nested Lists

List comprehensions can be used to create and manipulate nested lists concisely:

Python Code

# Creating a 3x3 matrix with zeros

matrix = [[0 for _ in range(3)] for _ in range(3)]

print(matrix) # Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

# Flattening a nested list

flat_list = [element for row in matrix for element in row]

print(flat_list) # Output: [0, 0, 0, 0, 0, 0, 0, 0, 0]

Example: A 3x3 Matrix Operations

Here is a more detailed example involving a 3x3 matrix:

Python Code

# Creating a 3x3 matrix

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

]

# Accessing an element

print("Element at (2, 3):", matrix[1][2]) # Output: 6

# Modifying an element

matrix[2][1] = 10

print("Modified matrix:", matrix)

# Iterating through the matrix

print("Iterating through matrix:")

for row in matrix:

for element in row:

print(element, end=' ')

print()

# Flattening the matrix

flat_list = [element for row in matrix for element in row]

print("Flattened list:", flat_list)

Multidimensional Lists

For more complex structures, you can have lists of lists of lists, and so on:

Python Code

# A 2x2x2 cube

cube = [

[

[1, 2],

[3, 4]

],

[

[5, 6],

[7, 8]

]

]

# Accessing an element

print(cube[0][1][1]) # Output: 4

Nested lists provide a flexible way to manage and manipulate complex data structures in Python. The key is understanding how to access, modify, and iterate through the elements at different levels of nesting.

Top of Form

Post a Comment

Previous Post Next Post