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
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)]
This way, each empty list in 'm' is a separate object, avoiding unwanted side effects.
Top comments (0)