I'm learning Python, and trying to figure out why the language treats numbers and arrays differently as global vs. local variables.
Here's an example: when I write a function to increment a numeric variable, the updated value is not preserved outside of the scope of that function. However, when I write a function to increment a numeric value within an array, the updated value is preserved outside of the scope of that function.
See below:
def addOne(num):
num += 1
def addOneToFirstElement(arr):
arr[0] += 1
var = 5
print var # Outputs '5'
addOne(var)
print var, "\n" # Outputs '5'
array = [4, 5, 6]
print array # Outputs [4, 5, 6]
addOneToFirstElement(array)
print array # Outputs [5, 5, 6]
Why does the language treat these two types of variables differently?