Objects and Variables#

Any time that data is processed in Python, an object is created in the computer’s memory. Every object contains at least 3 pieces of information: the type of object that it is (int, float, str, etc), the value of the object (3, -2.1, 'hello world', etc), and the reference count, which the computer uses to keep track of how many times the object is being referenced elsewhere in the program. Take for example the integer 1980. It’s type is int, it’s value is 1980, and for now it’s reference count is 0 because no named variables refer to it elsewhere in this program (we’ll go into more detail on reference counts in just a little bit).

You can check on an object’s type by using the type() function:

type(1980)
int

and you can check an object’s value by using the print() function:

print(1980)
1980

When objects are created in the computer’s memory, they are assigned an id value that describes where in the computer’s memory it’s stored. This id allows you to uniquely identify an object that’s been created. You can check the id of an object using the id() function.

id(1980)
1806449730640

We can imagine what computer thinks object this object using the following visual:

All the objects we’ve used so far are known as literal objects because their values are fixed and represented by the characters that make up the object. For example, 1980, 3.1, True, and 'hello' are all literal objects that have values implied by the characters used to represent them.

Variables#

In Python you can think about a variable as a name that has had object assigned to it. To create a variable, you assign it an object using a single equals sign (=).

x = 5
print(x)
5

In this case x is the variable, and 5 is the integer literal that it’s been assigned to.

You can see that when using the print() function with a variable the value of the object that’s been assigned to the variable is displayed. Using the type() function verifies that x is an integer.

type(x)
int

You can also see that a variable has the same id as the object it’s been assigned to.

id(x)
140708441330624
id(5)
140708441330624

We can visualize the relationship between the variable x and the object it points to using the following diagram. Notice that the reference count of the object has increased to 1, since there’s a variable that now refers to the object.

Lastly, when another variable is assigned to the same object as a previous variable, to save memory in the computer Python will direct the new variable to point to the already created object. This can be verified by checking the new variable’s id.

y = x
print(y)
id(y)
5
140708441330624

Now the memory of the computer would look something like the diagram below. Notice that now the reference count has increased to 2, since both x and y refer to the same object.

We’ll talk more about the specifics of objects throughout the course. For now it’s sufficient to know that:

  • Everything in Python is an object

  • Objects have types and values

  • Variables are only names that point to an object

  • Multiple variables can point to the same object

Garbage Collection#

Python uses the reference counter to identify when it’s safe to erase an object from the memory. When an object’s reference count reaches 0 it is deleted from memory which frees up room for additional objects to be stored. This process of erasing unreferenced objects is called garbage collection.

Other Object Types#

Below are other examples of variables and their associated object types.

a = 'hello'
type(a)
str
b = 3.1
type(b)
float
c = False
type(c)
bool

Using the type() function can be helpful to inspect what type of data you have stored to a variable if you are receiving error messages that state you are using the wrong data type.

Variable Names#

The examples you have seen so far have used short and non-descriptive names like x, y, a, and b. Programming best practices will suggest use of more descriptive variable names that indicate what type of data the variable refers to.

Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character ( _ ). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.

In order to make longer, multi-word variables more readable in your code, there are a variety of capitalization protocols you could use. All of these are standard, so choose which one best suits your style and use it consistently.

  • Camel Case: Second and subsequent words are capitalized, to make word boundaries easier to see.

Example: myFirstVariable

  • Pascal Case: Identical to Camel Case, except the first word is also capitalized.

Example: MyFirstVariable

  • Snake Case: Words are separated by underscores.

Example: my_first_variable

This course will typically use Snake Case when naming variables, as it’s the most common style used when programming in Python.

Reserved Names#

There are several (33 to be exact) variable names that are off-limits to you in Python, as they are reserved as keywords for other purposes. The list of keywords can be found by typing help("keywords") into the command line.

help("keywords")
Here is a list of the Python keywords.  Enter any keyword to get more help.

False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not