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.

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

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like