Creating list with lists inside by using multiply

list, python

Solution

If you want to create b with `a` in it twice:

a = []
b = [a] * 2

But beware, lists are mutable!

b[1].append('foo')
b
[['foo'], ['foo']]

If you want to create b with two copies of `a`:

b = [a[:] for i in range(2)]

For finer control over the nature of copies (vs bindings), read the python copy module documentation.

Problem

``` >>> a = [] >>> b = [a*2] >>> b [[]] >>> b = [copy.deepcopy(a)*2] >>> b [[]] ``` I'm trying to create `b` to be a list consisting of two copies of `a`. Why is `b` not `[[],[]]`? And how can I make it so that `b` is `[[],[]]`?

Original source