Frage

In python []*2, gives []

What is the simplest way to get [[],[]] instead?

War es hilfreich?

Lösung

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.

Andere Tipps

Use comprehension:

[[] for _ in range(2)]

That's because (e.g.) [1]*3 gives [1,1,1], i.e., a sequence containing the contents of the list.

Hence you want to duplicate the value []:

a = [[]]*2

giving

[[], []]

Because of the way the * operator works, this gives copies of the same list. Hence, if you try to modify either of those inner empty lists, it effects both of them. (Since they're empty, just about the only thing you can do is append to them; i.e., a[0].append(1) gives [[1],[1]].) This is possibly, but unlikely, what you want.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top