Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to vs. from a slice

When reading profile.py of python standard library I came across the assignment statement sys.argv[:] = args, which is used to modify sys.argv to make the program being profiled see the correct command line arguments. I understand that this is different from sys.argv = args[:] in the actual operations, but in effect they look the same to me. Is there a situation when one wants to use one and not the other? And is a[:] = b a common python idiom?

UPDATE: in this specific situation why would one choose one over the other? (source can be found in the main function of profile.py)

like image 315
Tony Beta Lambda Avatar asked Oct 17 '15 03:10

Tony Beta Lambda


1 Answers

The difference is, when you use a[:] = b it means you will override whatever is already on a. If you have something else with a reference to a it will change as well, as it keeps referencing the same location.

In the other hand, a = b[:] creates a new reference and copy all the values from b to this new reference. So existing references to the old data will keep pointing to the old data.

Consider this example:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a # c is a reference to the list in a
>>> c
[1, 2, 3]
>>> 
>>> a[:] = b
>>> a # a will have a copy of the list in b
[4, 5, 6] 
>>> c # and c will keep having the same value as a
[4, 5, 6]
>>>
>>> b = [7, 8, 9]
>>> a = b[:]
>>> a # a has the new value
[7, 8, 9]
>>> c # c keeps having the old value
[4, 5, 6]
like image 88
hugos Avatar answered Oct 19 '22 10:10

hugos