This is complicated, but when you multiply a list, you create a new list.
l = [1, 5, 9, 3] h = l
'l' and 'h' now refer to the same list in memory.
h[0], h[2] = h[2], h[0] print(h)
You changed the values ββin h , so the values ββchanged in l . It makes sense when you think of them as different names for the same object.
h = h * 2 print(h)
When you multiply h * 2 you create a new list, so now only the original list object will be l .
>>> 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 id of h changes after multiplication? The * operator creates a new list, unlike other list operations, such as append() , which modify the current list.
>>> h.append(1000) >>> id(h) 139753623282464
Hope this helps!
source share