'What is really the difference between += operation and append function in python lists? inside functions definations [duplicate]
So till now the only real difference that I knew about the difference in the append and += operation was that of speed but recently I stumbled upon a case in which += would throw an error while append would not can someone help out with what has been happening?
This code would not run and throw an error namely UnboundLocalError: local variable 'travel_log' referenced before assignment
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(Country,Visits,Cities):
travel_log+={"country":Country,"visits":Visits,"cities":Cities}
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
while this code would run
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
def add_new_country(Country,Visits,Cities):
travel_log.append({"country":Country,"visits":Visits,"cities":Cities})
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
Solution 1:[1]
While using the operator '+', you should create the list
travel_log = []
before using it.
def add_new_country(Country,Visits,Cities):
travel_log = []
travel_log+={"country":Country,"visits":Visits,"cities":Cities}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | baovolamada |
