What Is the Difference Between [[], []] and [[]] * 2

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

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

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.