Language: EN

python-tipos-valor-referencia

Value Types and Reference Types in Python

In Python, data types can be divided into two main categories: value types and reference types.

This is common in many programming languages. Understanding the differences between the two is very important, or you might elegantly mess up at some point 😉.

If you want to learn more about Value Types and Reference Types
check out the Introduction to Programming Course read more

Value Types

Value types in Python are those whose variables directly store the actual value. 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 such as 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 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 or memory address to the actual object instead of the actual value itself.

This means that when we assign a variable to another, both variables point to the same object in memory.

Common reference types include lists, dictionaries, sets, and custom objects.

For 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)  # Result: [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 must consider whether they are value types or reference types.

Passing value 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.

Passing reference types

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(lista):
    lista.append("New element")
    print("Inside the function:", lista)

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.