0

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?

Sam
  • 1,952
  • 1
  • 18
  • 31
  • The reason is that immutable types are not passed by reference. Python variables are passed by assignment. A `str` or an `int` in Python are immutable types, while a `list` (the "array" in your example) is mutable. So when you modify an `int` or `str`, you really just replace the old one with a new copy. – Will Jul 28 '15 at 20:23
  • you can also see http://stackoverflow.com/questions/2770038/python-create-a-function-to-modify-a-list-by-reference-not-value – Mazdak Jul 28 '15 at 20:24
  • @Will mutable and immutable types are both passed the same way – jonrsharpe Jul 28 '15 at 20:40
  • Hence why I said "Python variables are passed by assignment", not "certain types are passed this way, and others this way". – Will Jul 28 '15 at 22:11
  • @Will but your comment starts *"immutable types are not passed by reference"*, which at least implies that mutable types may be treated differently. – jonrsharpe Jul 29 '15 at 10:26
  • 1
    Very helpful. Thank you all! – Sam Jul 29 '15 at 15:45
  • @johnrsharpe You seem to be picking on details. Immutable types are not passed by reference, fact; both are passed "by assignment", but, for all intents and purposes, for mutable types, "assignment" assigns a reference. I'm under the impression that an actual copy of an integer would be assigned, rather than a reference to the original integer, which is immutable... If I pass `x` in as an arg, and assign a new value to it (`x+1`), the passed-in argument in the outside scope doesn't get reassigned. If I tried to assign a new value to a mutable arg, the outside reference would update. – Will Jul 29 '15 at 20:43

0 Answers0