Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to lists in Python 2.7

>>> 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?

like image 823
stillanoob Avatar asked Nov 16 '15 14:11

stillanoob


People also ask

How do I add elements to a list in Python?

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().

Can you add to a list in Python?

Python provides a method called . append() that you can use to add items to the end of a given list.

Can I use += to append to list in Python?

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.

How do you add two values in a list in Python?

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.


1 Answers

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.

like image 72
Nhor Avatar answered Oct 05 '22 14:10

Nhor