DEV Community

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

Posted on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay