A sequence of empty lists of length n in Python?

list, python, sequence

Solution

You probably want:

[[] for _ in range(n)]

Unlike `[[]] * n`, this will give you unique inner lists (appending to one doesn't append to them all). e.g.:

>>> x = [[] for _ in range(n)]
>>> x[0].append(1) 
>>> x
[[1], [], []]

compared to:

>>> x = [[]] * 3
>>> x[0].append(1)
>>> x
[[1], [1], [1]]

Note that this latter idiom (`[[]] * n`) is a very common mistake that crops up around here in different contexts pretty frequently.

Problem

In python `[]*2`, gives `[]` What is the simplest way to get `[[],[]]` instead?

Original source

Related problems