>>> A = [1,2,3,4]
>>> D = A
>>> D
[1, 2, 3, 4]
>>> D = D + [5]
>>> A
[1, 2, 3, 4]
>>> C = A
>>> C += [5]
>>> A
[1, 2, 3, 4, 5]
Why does C += [5]
modifies A
but D = D + [5]
doesn't?
Is there any difference between =
and +=
in python or any other language in that sense?
list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right. list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
Python provides a method called . append() that you can use to add items to the end of a given list.
For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.
The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists.
Actually yes there is. When you use +=
you're still referencing to the same object, however with +
you're creating a new object, and with =
you reassign the reference to that newly created object. This is especially important when dealing with function arguments. Thanks to @Amadan and @Peter Wood for clarifying that.
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