Dmytro Hrimov

Senior software engineer

Python basic concepts

Overview

To start a series of Python posts, I wanted to share some basic Python concepts that everything is built on top of.

First, let's look at what a variable is and what an object is in Python.

Variable vs Object

A Python object is a concrete piece of information in a specific memory position on your computer.

In contrast, a variable in Python is an entity that points to an object in memory. In other words, a variable refers to a specific object or holds a reference. Variables do not have any type or size associated with them because variables do not store any values on their own.

Both of these concepts are independent of each other but are closely related.

Once you declare a variable and assign a value to it, you effectively create an object in memory and make a variable point to it. You can then access this object in memory by using a value or making operations on the object.

It's important to note that in Python, you won't be able to access that object in your code if you don't have a reference (variable) to an object. Additionally, if you lose or remove all the references to a specific object, Python's automatic garbage collection will free up the memory used by that object for later use.

What is a Python object?

In Python, everything is an object. Strings, numbers, classes, and functions are all objects.

Every Python object has three core characteristics that define it at a foundational level: Value, Identity, and Type.

The most familiar ones here are Value and Type. An object's value is a piece of data that it stores.

Let's take a look at this example:

>>> 13

13

>>> isinstance(13, int)

True

>>> type(42)

<class 'int'>

The numeric value, 13 is an object. This object is an instance of a built-in type - int.

In Python, every object has a unique identifier known as its identity, which corresponds to its specific memory address for the CPython implementation. This identity is a read-only property that sets the object apart from others. You can utilize the built-in id() function to retrieve an object's identity.

>>> id(13)

1470963258

Conclusion

In this short article, we examined one of the most fundamental concepts in Python: objects and variables. We also examined object characteristics to build on this information going forward.