Referencing Objects In Python

We got a quick look at some of the data types we can work with in Python. Now we need to see how we can make reference to our data for future use. In Python, we assign values to variables using the equal to sign (=).

This is done by entering variable = value. What then happens is that Python creates an object in memory (the value) and makes a reference to it (the variable). So in a manner of speaking, the variable is only pointing to the value.

If we were to have two variables var1 and var1 and we make var1 = "white" and var2 = var1, what happens is that Python makes var2 to reference the object which var1 is currently referencing (“pink”). If we then make var1 reference a different object var1 = "pink", Python creates the new object “white” in memory and points var1 to it. Since var2 is referencing the object and not var1, its value will not change.

This is important to note as it can lead to some tricky situations which we will see in the future.

Another thing to note is the rules which govern choosing variable names. Names are case sensitive so for example VAR1, Var1 and var1 will be stored as 3 different variables. They must also begin with either an underscore or a letter which can not be followed by spaces of any kind (other Unicode characters are allowed). Names are not allowed to coincide with Python keywords (some of these include but are not limited to int, str, float, and complex like we saw earlier)

Next, we will take a closer look at the data types lists and tuples.

Leave a Reply

Your email address will not be published. Required fields are marked *