Neshan Kaluarachchi Neshan Kaluarachchi - 8 days ago 6
Python Question

Python regarding changing values without using global or reassigning

I am struggling with a python question. In the below code, I have to reassign str1 and str2 to the values passed inside the function zero... We were asked not to set a global variable and not to use str1,str2 = zero(s1,s2) which kinda doesn't make sense for me as to why we shouldn't.

Please be kind enough to help me figure this out! THANK YOU!

This is what I have got so far...

def zero(s1,s2):

#Initial values passed into the function
print("Start of ZERO s1 is :" , s1)
print("Start of ZERO s2 is :" , s2)

#setting new values for s1 and s2
s1 = [1,2,3]
s2 = [4,5,6]

#printing changes new values of s1 and s2
print("\nEnd of ZERO s1 is ", s1)
print("\nEnd of ZERO s2 is ", s2)

return s1,s2

str1 = 'spam'
str2 = {1:'m' , 'p' : 'a'}

#values of str1 and str2 which should be changed to s1 and s2 inside the function should be here......

Answer

One way I can think of doing it is, which is a bit sneaky, is to put str1 and str2 into a dict and have the function alter the dict.

Since unless you deep copy a dict you are making a reference still to the same object, so when you mutate it you mutate the underlying object.

I would modify your code as follows:

def zero(str_dict):

    s1 = str_dict['str1']
    s2 = str_dict['str2']

    #Initial values passed into the function
    print("Start of ZERO s1 is :" , s1)
    print("Start of ZERO s2 is :" , s2)

    #setting new values for s1 and s2
    s1 = [1,2,3]
    s2 = [4,5,6]

    #printing changes new values of s1 and s2
    print("\nEnd of ZERO s1 is ", s1)
    print("\nEnd of ZERO s2 is ", s2)

    str_dict['str1'] = s1
    str_dict['str2'] = s2

str1 = 'spam'
str2 = {1:'m' , 'p' : 'a'}

#values of str1 and str2 which should be changed to s1 and s2 inside the function should be here......

Now to test:

str_dict = {
    "str1": str1,
    "str2": str2
}

print str_dict

zero(str_dict)

print str_dict

I see the following output:

{'str2': {1: 'm', 'p': 'a'}, 'str1': 'spam'}
('Start of ZERO s1 is :', 'spam')
('Start of ZERO s2 is :', {1: 'm', 'p': 'a'})
('\nEnd of ZERO s1 is ', [1, 2, 3])
('\nEnd of ZERO s2 is ', [4, 5, 6])
{'str2': [4, 5, 6], 'str1': [1, 2, 3]}
Comments