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.
() 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.
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.
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]
[:] 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.
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)]
[[]] * 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With