DEV Community

Cover image for A list of lists in Python
Siddharth Singh Tanwar
Siddharth Singh Tanwar

Posted on

A list of lists in Python

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.

Top comments (0)