A list of lists in Python
Siddharth Singh Tanwar

Siddharth Singh Tanwar @siddharth_singhtanwar_6a

About: Taking ownership of my code

Joined:
Jun 17, 2024

A list of lists in Python

Publish Date: Jul 14 '24
1 0

Python Tip: Creating a List of Lists

When creating a list of lists in Python, it's important to understand how list multiplication works.

Using:

m = [[]] * 7
Enter fullscreen mode Exit fullscreen mode

creates seven references to the same list. Modifying one list will affect all others because they reference the same object.

Instead, use list comprehension to ensure each list is independent:

m = [[] for _ in range(7)]
Enter fullscreen mode Exit fullscreen mode

This way, each empty list in 'm' is a separate object, avoiding unwanted side effects.

Comments 0 total

    Add comment