2

Why in the first code the function update created a local variable with the same name (integ) without affecting the global integ while in the second code it changed the global value of list and didn't create a local list with the same name?

integ = 5
def update(integ):
    integ += 2
update(integ)
print(integ)


list = [1,10]
def update2(list):
    list += [2]
update2(list)
print(list)
nos
  • 223,662
  • 58
  • 417
  • 506
Amr Dawoud
  • 21
  • 3
  • 2
    Ultimately this is because lists are mutable. The global reference to `list` hasn't changed, its contents have. That's not a thing with numbers. – Adam Smith Oct 12 '18 at 23:58
  • 3
    `+=` on a list (somewhat misleadingly) mutates the list. `+=` on an int only reassigns the variable. – khelwood Oct 13 '18 at 00:05
  • use the keyword `global` within a function to refer to a global variable. – Pika Supports Ukraine Oct 13 '18 at 00:09
  • 2
    Try assigning to `list` rather than mutating the existing list, eg `list = list + [2]`. That behaves exactly the same as the example where you assign a new integer object to the name `integ`. – PM 2Ring Oct 13 '18 at 00:16
  • 1
    See also https://stackoverflow.com/q/20699736/1256452 – torek Oct 13 '18 at 00:17
  • 3
    BTW, please don't shadow the built-in `list` type. It can lead to odd error messages if you later try to call `list`. And when you use it in example code like this it can make it confusing when people want to talk about your code. – PM 2Ring Oct 13 '18 at 00:19

0 Answers0