Sobes.tech
Middle

What is a variable in Python? How is it passed to a function?

sobes.tech AI

Answer from AI

In Python, a variable is a name that refers to an object in memory. Variables do not have a fixed type; the type is determined by the object they refer to.

When passing a variable to a function, a reference to the object is passed, not a copy of the value. This means that if the object is mutable (e.g., a list), changes inside the function will affect the original. If the object is immutable (e.g., a number or string), then attempting to change it inside the function creates a new object, and the original remains unchanged.

Example:

def modify_list(lst):
    lst.append(4)

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list)  # Outputs [1, 2, 3, 4]


def modify_int(x):
    x += 1

num = 5
modify_int(num)
print(num)  # Outputs 5

Thus, the behavior depends on the type of the object the variable refers to.