How do I create a nested list?

To create a nested list in Python, you can define a list that contains other lists as its elements. Here's a simple example:

# Creating a nested list
nested_list = [
    [1, 2, 3],       # First sublist
    [4, 5, 6],       # Second sublist
    [7, 8, 9]        # Third sublist
]

# Accessing elements
print(nested_list[0])      # Output: [1, 2, 3]
print(nested_list[1][2])   # Output: 6 (third element of the second sublist)

In this example, nested_list contains three sublists. You can access elements using indexing, where the first index refers to the sublist and the second index refers to the element within that sublist.

If you want to learn more about manipulating nested lists, consider exploring related labs on LabEx!

0 Comments

no data
Be the first to share your comment!