From https://docs.python.org/2/library/copy.html
Shallow copies of dictionaries can be made using dict.copy(), and of lists by
assigning a slice of the entire list, for example, copied_list = original_list[:].
OK
def do_something(a, b):
a.insert(0, 'z') #this is still referencing a when executed. a changes.
b = ['z'] + b #This is a shallow copy in which the b in this function, is now [’a’, ’b’, ’c’, 'z'].
Although the above is true, the b you are thinking of that has the 'z' is not the same b that will be printed at the "end" of the program. The b printed on the first line though, is the b in the function def_something().
Code:
def do_something(a, b):
a.insert(0, 'z') #any changes made to this a changes the a that was passed in the function.
b = ['z'] + b #This b is do_something() local only. LEGB scope: E. Link below about LEGB.
print("a b in function: ", a, "|", b)
a = ['a', 'b', 'c']
a1 = a
a2 = a[:] #This is never touched following the rest of your code.
b = ['a', 'b', 'c']
b1 = b
b2 = b[:] #This is never touched following the rest of your code.
print("a b before function: ", a, "|", b)
do_something(a, b)
print("a b after function: ", a, "|", b) #This b is same thing it was after assignment.
Output:
a b before function: ['a', 'b', 'c'] | ['a', 'b', 'c']
a b in function: ['z', 'a', 'b', 'c'] | ['z', 'a', 'b', 'c']
a b after function: ['z', 'a', 'b', 'c'] | ['a', 'b', 'c']
More info on LEGB.