Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between [[],[]] and [[]] * 2

Tags:

python

t0 = [[]] * 2                                                                   
t1 = [[], []]                                                                   

t0[0].append('hello')                                                           
print t0                                                                        

t1[0].append('hello')                                                           
print t1             

The result is

[['hello'], ['hello']]
[['hello'], []]

But I can't tell their difference.

like image 821
hello.co Avatar asked May 24 '13 02:05

hello.co


People also ask

What is difference between [] and () in Python?

() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.

Whats the difference between {} and [] in JavaScript?

The difference between “{}” and “[]” is that {} is an empty array while [] is a JavaScript array, but there are more! In JavaScript, almost “everything” is an object. All JavaScript values, except primitives, are objects. Therefore if you understand objects, you understand JavaScript.

What does 0 ]* n mean in Python?

X = [0] * N creates an array of zeros of N length. For example: >>> [0] * 10 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

What is a [:] in Python?

[:] is the array slice syntax for every element in the array. This answer here goes more in depth of the general uses: Explain Python's slice notation.


2 Answers

When you do [[]] * 2, it gives you a list containing two of the same list, rather than two lists. It is like doing:

a = []
b = [a, a]

The usual way to make a list containing several different empty lists (or other mutable objects) is to do this:

t1 = [[] for _ in range(5)]
like image 68
lvc Avatar answered Oct 31 '22 23:10

lvc


[[]] * 2 

makes a shallow copy. Equivalent to:

x = []
t0 = [x, x]

However

t1 = [[], []]

Uses two separate empty list literals, they are completely different so mutating one obviously doesn't mutate the other

like image 45
jamylak Avatar answered Nov 01 '22 01:11

jamylak