hello.co
hello.co

Reputation: 756

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

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.

Upvotes: 5

Views: 2344

Answers (2)

jamylak
jamylak

Reputation: 133534

[[]] * 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

Upvotes: 7

lvc
lvc

Reputation: 35059

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)]

Upvotes: 10

Related Questions