2

When I use the += in my function, I get this error: UnboundLocalError: local variable 'travel_log' referenced before assignment but it totally works with the append() function. What is the difference?

travel_log = []
def add_new_country(countries_visited, times_visited, cities_visited):
    new_country = {}
    new_country["country"] = countries_visited
    travel_log += new_country
Delaram
  • 21
  • 2

2 Answers2

2

Because you assigned to travel_log in your add_new_country function (+= is an assignment), it is considered a local variable in that function. Because it is a local variable, and you never assigned it a value, travel_log has no value when you attempt to += to it. Python does not fall back to using the global variable of the same name.

This is somewhat surprising because the += operation on a list is equivalent to calling its extend() method, and the name remains bound to the same list. The error feels more reasonable when the variable is a number or some other immutable object. But it's the same behavior.

If you want to operate on the global variable, say so:

def add_new_country(countries_visited, times_visited, cities_visited):
    global travel_log
    # etc.

But it's better to use travel_log.append(). Appending isn't an assignment, so it doesn't make travel_log local.

kindall
  • 178,883
  • 35
  • 278
  • 309
1

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in add_new_country() assigns a new value to travel_log, the compiler recognizes it as a local variable.

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be local unless explicitly declared as global.

So in your case, declare travel_log as global scope inside the function

travel_log = []

def add_new_country(countries_visited, times_visited, cities_visited):
    # now function will refer the globally declared variable
    global travel_log
    new_country = {}
    new_country["country"] = countries_visited
    travel_log += new_country

Checkout this blog for a detailed explanation: https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Mohit Patil
  • 305
  • 1
  • 4
  • 11