A list of lists in Python

Siddharth Singh Tanwar - Jul 14 - - Dev Community

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.

. . . .
Terabox Video Player