Skip to main content

Deeper into Python value change inside functions

 https://www.dataquest.io/blog/tutorial-functions-modify-lists-dictionaries-python/

number_1 = 5
number_2 = 10

def multiply_and_add(number_1, number_2):
    number_1 = number_1 * 10
    number_2 = number_2 * 10
    return number_1 + number_2

a_sum = multiply_and_add(number_1, number_2)
print(a_sum)
print(number_1)
print(number_2)
150
5
10 

number_1 and number_2 did not change although they were global variables.

because python stores global and local variables at different memory locations

 def add(x: float, y: float) -> float:

    return x+y

this is syntax only. even if you pass strings it will work.

initial_list = [1, 2, 3]

def duplicate_last(a_list):
    last_element = a_list[-1]
    a_list.append(last_element)
    return a_list

new_list = duplicate_last(a_list = initial_list)
print(new_list)
print(initial_list)
[1, 2, 3, 3]
[1, 2, 3, 3]
global value of initial_list was updated, even though its value was only changed inside the function!

content_ratings = {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622}

def make_percentages(a_dictionary):
    total = 0 # calculate the total of all values
    for key in a_dictionary:
        count = a_dictionary[key]
        total += count
    # convert each value into percentage
    for key in a_dictionary:
        a_dictionary[key] = (a_dictionary[key] / total) * 100

    return a_dictionary
c_ratings_percentages = make_percentages(content_ratings)
print(c_ratings_percentages)
print(content_ratings)
{'4+': 61.595109073224954, '9+': 13.714047519799916, '12+': 16.04835348061692, '17+': 8.642489926358204}
{'4+': 61.595109073224954, '9+': 13.714047519799916, '12+': 16.04835348061692, '17+': 8.642489926358204}

The dictionary value changes.

So what’s actually happening here? We’ve bumped up against the difference between mutable and immutable data types.

immutable (integers, floats, strings, Booleans, and tuples)
lists and dictionaries are mutable




list.copy() # makes a copy of a list 
dict.copy() # makes a copy of a dict




list inside tuple is mutable