It's tricky, but when you multiply a list, you are creating a new list.
l = [1, 5, 9, 3]
h = l
'l' and 'h' are now referring to the same list in memory.
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
You swapped the values in h
, so the values are changed in l
. This makes sense when you think about them as different names for the same object
h = h * 2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
When multiplying h * 2
, you are creating a new list, so now only l
will be the original list object.
>>> l = [1, 5, 9, 3]
>>> h = l
>>> id(h) == id(l)
True
>>> id(h)
139753623282464
>>> h = h * 2
>>> id(h) == id(l)
False
>>> id(h)
139753624022264
See how the id
of h
changes after the multiplication? The *
operator creates a new list, unlike other list operation, such as append()
which alter the current list.
>>> h.append(1000)
>>> id(h)
139753623282464 # same as above!
Hope this helps!