You have a problem with your function definitions. You are passing both functions an argument, thus making it unnecessary to declare anything global in the first place. If you would remove the arguments from your definitions, this question would make a little more sense.
The whole confusion here lies within mutability of data types in python. Lists and dictionaries are mutable containers, which means that their values can be changed at any time. Other data types, like integers, floats, tuples and so on are immutable. You cannot change them. You can create new ones, like 1 + 1
will return a new integer 2
.
In your first example, you're modifying the contents of a list. Lists are mutable containers which means that their contents can change. If you happen to have a
in the global scope, then a function in that same scope can modify the contents of the list.
def foo():
""" Notice i've removed the argument `a` from the function def, to illustrate my point.. """
for i in range(a[0].__len__()):
a[0][i] -= a[1][i]
>>> a = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]
>>> foo()
>>> print(a)
[[0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6]]
In your second example, you're modifying an integer. Integers are immutable data types and cannot be modified. The following will modify the variable a
(by creating a new integer) in the local scope of function foo()
but because you have not defined a
global or return the local a
, there's no visible change.
def foo(a):
a -= 1
>>> a = 2
>>> foo(a)
>>> print(a)
2