What is the method for nesting lists in Python?

In Python, list nesting refers to including another or multiple lists within a single list. This can be achieved by adding other lists in the form of lists within a list. For example:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the example above, nested_list is a list that contains three sub-lists: [1, 2, 3], [4, 5, 6], and [7, 8, 9].

You can access elements in a nested list using the following methods:

print(nested_list[0])  # 输出第一个子列表 [1, 2, 3]
print(nested_list[0][1])  # 输出第一个子列表的第二个元素 2

One option is to use loops to iterate through all elements in a nested list.

for sublist in nested_list:
    for element in sublist:
        print(element)
bannerAds