L = [1,2,3,4]
L.append(13) # (1)
L = L + [13] # (2)
What is difference in above statements?
L = [1,2,3,4]
L.append(13) # (1)
L = L + [13] # (2)
What is difference in above statements?
L.append(13)
appends 13 to an existing list.
L = L + [13]
creates a new list.
L.append(13)
adds a single item, the int 13
, to the end of the list.
L = L + [13]
adds every item in a secondary list to the end of the first list. So you could have written L = L + [12, 4, 13]
and it would add all three.
Moreover, append
adds 13
to the end of an existing list....in the computer's memory, L
is still the same list, just with a new item added into it. But whenever you use the =
operator*, you're creating something new. So L = L + [13]
is creating a new list in the computer's memory, assigning it the name L
and filling it with the contents of the old L
concatenated with the list [13]
.
*If you do var1 = var2
, however, it's not creating something new but rather assigning the name var1
to point to the same place in memory as var2
.