more on bad python

Python is very convenient because we don’t have to type each variable, but this can also lead to sloppy mistakes.  A common mistake occurs when two variables point to the same memory and operations on one variable also changes the value of the other. This is not a problem for ‘simple’ objects like floats or strings, where x = y is equivalent to x = copy.deepcopy(y), but it is an issue for more complex data structures like lists and dicts.

For example, let x = [1,2]. If we say y = x, then x and y are point to the same memory that holds [1,2]. x.append(3) acts on this memory and changes both x and y to [1,2,3]. However, if we set x = [1,2,3], then x is pointing at a different memory holding [1,2,3] while y is still pointing at the original [1,2], so the variables become disjoint. If the RHS of ‘=’ is a variable, then the LHS is pointed to the memory associated with the RHS. If RHS of ‘=’ is a concrete object like a string or list or dict, then a new piece of memory is created and the LHS variable now points to it. Also, if the RHS is var + something, then a new memory is created. Variables are not tied to other variables, but only points to specific memory.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s