python 3.x - Why dict is reachable out of function, but list is not? -
three use cases:
1) dict interests
reachable
interests = {} def get_interests(): print('interests:', interests) # interests: {} interests['somekey'] = 123 print('interests:', interests) # interests: {'somekey': 123} get_interests()
2) list interests
not reachable
interests = [] def get_interests(): print('interests:', interests) # unboundlocalerror: local variable 'interests' referenced before assignment interests += [123] print('interests:', interests) get_interests()
3) in case of list, if print
, works
interests = [] def get_interests(): print('interests:', interests) # interests: [] # interests += [123] # print('interests:', interests) get_interests()
what did miss?
try .append()
on list:
interests = [] def get_interests(): print('interests:', interests) # unboundlocalerror: local variable 'interests' referenced before assignment interests.append(123) print('interests:', interests) get_interests()
the reason you're seeing behavior using +=
operator you're telling python following: interests = interests + [123]
-- declares new variable called "interests" in scope of function instead of modifying global variable "interests".
by using .append()
function you're not creating new variable modifying global variable instead.
Comments
Post a Comment