In Python, data types can be divided into two main categories: value types and reference types
This is something common in many programming languages. Understanding the differences between both is very important (or you might elegantly mess up at some point 😉).
If you want to learn more about Value and Reference Types
check out the Introduction to Programming Course read more
Value Types
Value types in Python are those whose variables store the actual value directly. This means that when we assign a variable to another value, a new copy of that value is created in memory.
The most common value types in Python are basic types like integers, floats, strings, and booleans.
For example,
# Assigning an integer to a variable
x = 10
# A new copy of the value 10 is created in memory for the variable x
y = x
# Now x and y have independent values in memory
When we modify x
or y
, each variable has its own space in memory to store its value.
Reference Types
Reference types are those whose variables store a reference (usually the memory address) to the actual object instead of the actual value itself.
This means that when we assign one variable to another, both variables point to the same object in memory.
Common reference types include lists, dictionaries, sets, and custom objects.
Let’s see it with an example.
# Assigning a list to a variable
list1 = [1, 2, 3]
# list2 points to the same object in memory as list1
list2 = list1
# Modifying list2 also modifies list1
list2.append(4)
print("list1:", list1) # Output: [1, 2, 3, 4]
In this example, when we modify list2
, list1
is also modified because both variables point to the same object in memory.
Passing Arguments to Functions
When we pass variables to functions, we need to consider whether they are value types or reference types.
Value types are not modified when passed as parameters because the function receives a copy.
def double_number(num):
num *= 2
print("Inside the function:", num)
x = 10
double_number(x)
print("Outside the function:", x) # x remains 10, it was not modified
The value of x
is not modified outside the double_number
function because it is a value type.
Reference types are modified when passed as parameters because the function receives a copy of the reference, which points to the same data.
def modify_list(lst):
lst.append("New element")
print("Inside the function:", lst)
my_list = [1, 2, 3]
modify_list(my_list)
print("Outside the function:", my_list) # my_list is modified
In this case, my_list
is modified outside the function because it is a reference type.