Defining variables within a function

  1. i understand a variable created within a function can only be called inside that same function. i think that is correct. right?

  2. once a variable is assigned inside a function, you can call it inside that same function as many times as you want. correct?

  3. if the above two statements are correct, why does the following code not function correctly? or at least produce what i’m trying to produce. it produces something, just not what i’m looking for.

def append_sum(lst):
    last_two_added = lst[-2] + lst[-1]
    lst.append(last_two_added)
    lst.append(last_two_added)
    lst.append(last_two_added)
    return lst

print(append_sum([1, 1, 2]))

this way works…

def append_sum(lst):
    last_two_added = lst[-2] + lst[-1]
    lst.append(last_two_added)
    last_two_added = lst[-2] + lst[-1]
    lst.append(last_two_added)
    last_two_added = lst[-2] + lst[-1]
    lst.append(last_two_added)
    return lst

print(append_sum([1, 1, 2]))

this way works as well…

def append_sum(lst):
    lst.append(lst[-1] + lst[-2])
    lst.append(lst[-1] + lst[-2])
    lst.append(lst[-1] + lst[-2])
    return lst

    print(append_sum([1, 1, 2]))

just wondering why i can’t assign the variable one time and call it for each of the appends. why do i have to assign it each time?

thanks!

yes, this is known as local scope.

in the first code sample, you retrieve the last and second to last value from the list once, and append this value multiple times

in the second and third code sample, you get the last and second to last value from the list multiple times, given the list is changing, these values change as well.

1 Like

so when i call that variable it’s calling the results of the original list? not the new appended list?

the values assigned to the variable are copies of the values from the list, so unless you update the variable (like in example 2), the variable will keep the same values

1 Like

got it. thanks so much! very helpful. cheers!