Creating a List with Lists Inside Using Multiplication

>>> a = []
>>> b = [a*2]
>>> b
[[]]
>>> b = [copy.deepcopy(a)*2]
>>> b
[[]]

I am trying to create bto be a duplicate list a. Why bnot [[],[]]? And how can I make it so that bwas [[],[]]?

+3
source share
3 answers

If you want to create b c ain it twice:

a = []
b = [a] * 2

But be careful, the listings are mutable !

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

If you want to create b with two copies a:

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

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

+5
source

You can try this b = [a for i in xrange(2)]

0
source

* 2 - , , . :

a = [1]
b = [2]
a + b
[1, 2]

, [[1], [2]] - , . .

So, in these lines it [] * 2generates a list like [], because you would also get it if you did [] + []- a list with all the elements from both lists in it, which, since both entries are empty, are also empty. And then, you put it on another list, in the end you get [[]].

Other answers already cover other ways of generating this, so I will not duplicate them.

0
source

All Articles