A “Python nested list” refers to a data structure in Python that allows you to have lists within lists. In other words, it is a list that contains other lists as elements. The concept of nesting lists enables the creation of hierarchical or multi-dimensional data structures.
A nested list can have any number of levels of nesting, allowing for the representation of complex data structures. Each level of nesting represents a dimension in the structure. For example, a nested list with two levels of nesting can be seen as a 2D matrix, where the outer list represents the rows and the inner lists represent the columns.
The syntax for creating a nested list in Python is quite straightforward. Here’s an example:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In the above example, nested_list
is a variable that holds a nested list. The outer list contains three inner lists, each representing a row in a 2D matrix.
To create a nested list, you enclose the elements of each sublist within square brackets [ ]
and separate them with commas. The outer list also uses square brackets to encompass the inner lists.
You can have any number of levels of nesting, allowing you to create multi-dimensional data structures. Here’s an example with three levels of nesting:
nested_list = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
In this example, nested_list
is a nested list with two outer lists. Each outer list contains two inner lists. Finally, each inner list holds two elements.
You can access, modify, and manipulate the elements within nested lists using indexing and other list operations.
Python nested list example
Here’s a demonstration of how you can access, modify, and manipulate elements within nested lists using indexing and other list operations in Python:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing elements
print(nested_list[0]) # [1, 2, 3]
print(nested_list[1][2]) # 6
print(nested_list[2][0]) # 7
# Modifying elements
nested_list[1][1] = 10
print(nested_list) # [[1, 2, 3], [4, 10, 6], [7, 8, 9]]
# Adding elements
nested_list.append([10, 11, 12])
print(nested_list) # [[1, 2, 3], [4, 10, 6], [7, 8, 9], [10, 11, 12]]
# Removing elements
nested_list.pop(1)
print(nested_list) # [[1, 2, 3], [7, 8, 9], [10, 11, 12]]
Output:
You can also add elements to a nested list using the append()
method, which appends a new sublist to the end of the list. Similarly, you can remove elements using the pop()
method, which removes a sublist at a specified index.
Remember that nested lists can have different lengths for each sublist. This means you can create irregular or jagged matrices where each row has a different number of elements.
Comment if you have any doubts or suggestions on this Python List topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.