How to Create a List of Lists in Python?

Estimated read time 1 min read

In Python, you can create a list of lists by nesting one or more lists inside another list. Here’s an example:

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

This creates a list of three sublists, each containing three integers. You can access elements of the sublists by using two indices, one for the outer list and one for the inner list. For example:

print(my_list[0][1])  # Output: 2
print(my_list[1][0])  # Output: 4

You can also add or remove sublists or elements from the sublists using list methods. Here are some examples:

# Adding a new sublist
my_list.append([10, 11, 12])

# Removing an element from a sublist
del my_list[0][1]

# Removing a sublist
my_list.remove([4, 5, 6])

# Modifying an element in a sublist
my_list[2][1] = 100

By nesting lists, you can create more complex data structures in Python, such as matrices or tables.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply