Code like a Pythonista - assignments in Python

Code like a Pythonista - assignments in Python

I mainly use C++ programming language, but I always wanted to try Python, which allows you to prototype more quickly than C++. Now I work as a Python programmer.

I found it difficult to understand how does arguments copying work in python. C++ was obvious - you can pass an argument to function by value, by reference or by pointer. Passing by value creates a copy, so your original object won't be changed.

How is it in Python? Please first take a look at this code:

def add_something(my_list):
    my_list.append("world")
    print("Inside append_something:", my_list)

def overwrite_something(my_list):
    my_list = my_list + ["world"]
    print("Inside overwrite_something:", my_list)

l = ["hello"]
overwrite_something(l)
print("After overwrite:", l)
add_something(l)
print("After append:", l)

 

And the oputput is...

Inside overwrite_something: ['hello', 'world']
After overwrite: ['hello']
Inside append_something: ['hello', 'world']
After append: ['hello', 'world']

I was confused by the fact that if you pass a list it sometimes get modified, sometimes not. I only knew which objects are mutable (they change when passing) and which are immutable (they won't change). List is mutable, so I thought that it should always change. But it doesn't work like this. I finally found a very simple explanation to my problem.

Python doesn't have a variables like C++. It has identifiers (but to be compliant with all programming languages we call them variables).  Identifiers are like labels. When you assign a value to identifier you put a label on that object. When you assign identifier a to identifier b, you put another label on object. It's not a copy.

So if you pass something as a function argument and then you assign something else to that variable it won't be visible outside, because outside you use your original identifier, which still points to your old object. But if you use method of that object, like append in the example above - the object gets modified, so even your external variable shows you that object is modified.

For a greater explanation (and many more Python quirks) please visit http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

 

No feedback yet
Leave a comment

Your email address will not be revealed on this site.
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)