Python Forum

Full Version: output values change
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
int the below code:
def something(num,my_list):
    num=3
    my_list[0]=3

a=2
b=[2]
something(a,b)
print(a)
# 2 is printed
print(b)
#[3] is printed
the value of a in the final is the same as before, but the b value has changed. Why?
I read somewhere something before it, but i can not understand it. can you explain it?
thanks
a and b are just names used to reference objects. The names are of no importance here.

a references an int object. Int objects are immutable, they cannot change. 2 is always 2, and you cannot change 2 to 3. You can reassign a variable to reference a different int object. num first referenced 2, then was assigned to reference 3. The only relationship between a and num is that the int object referred to by a was passed to a function as the argument num. The variables a and num know nothing about each other. Even if you rewrote the function to look like below.
def something(a,b):
    a=3
    b[0]=3
The function arguments a and b have no relationship with the global variables a and b. They just happen to have the same names.

b references a list. Lists are mutable, they can be changed. Your function changes the list object so it holds the int object 3 instead of 2.

The "value of" a and b do not change in your program. a always refers to the int object 2, and b always refers to the same list object.
(Oct-17-2023, 11:09 AM)deanhystad Wrote: [ -> ]a and b are just names used to reference objects. The names are of no importance here.

a references an int object. Int objects are immutable, they cannot change. 2 is always 2, and you cannot change 2 to 3. You can reassign a variable to reference a different int object. num first referenced 2, then was assigned to reference 3. The only relationship between a and num is that the int object referred to by a was passed to a function as the argument num. The variables a and num know nothing about each other. Even if you rewrote the function to look like below.
def something(a,b):
    a=3
    b[0]=3
The function arguments a and b have no relationship with the global variables a and b. They just happen to have the same names.

b references a list. Lists are mutable, they can be changed. Your function changes the list object so it holds the int object 3 instead of 2.

The "value of" a and b do not change in your program. a always refers to the int object 2, and b always refers to the same list object.

hi
good explenation and thanks, but can explain more?
thanks again
Mutable vs immutable sums it all up. The mutable list object was changed. The immutable int object was not changed. If you have more questions, ask them. I am not going to guess what they might be.