Python-Ref > Basic usage > Moving objects around > Passing by value vs. by reference
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

Passing by value vs. by reference

When a content of one variable is assigned to another variable or passed as an argument to a function, the value may be passed in two different ways - either by value or by reference.
What does it mean? When a variable is passed by value, it is in fact copied to the the new destination without any further 'link' to the old destination. Conversely, passing by reference means that the new variable simply points to the same object as the old one. This is, a change in the object from the new destination changes also the value seen from the old destination and vice versa. This is because the two in fact are the same object.
Passing by value is common for un-mutable simple types, such as numbers, strings and tuples.
Passing by reference is used in all other cases, that is for more complex, mutable types, such as lists, dictionaries, class instances (objects), etc.
Expand/Shrink
Zdroj: (passing1.1.py)
  1   str1 = "hello"
  2   str2 = str1
  3   str2 += " David"
  4   print str1   # unaffected by change in str2
  5   print str2
  6   
  7   list1 = [1,2,3,4]
  8   list2 = list1
  9   list2 += [5]
 10   print list1  # both are the same
 11   print list2
stdout:
hello
hello David
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Doba běhu: 20.9 ms
Passing by reference is most of the times the thing you want. However in some cases it might have some unforseen consequences.
The following code shows a naive code creating a zero matrix. However changing of some value in tha matrix has unexpected consequences.
Expand/Shrink
Zdroj: (passing1.2.py)
  1   # at first we create a matrix by copying of an empty line
  2   empty_line = [0,0,0]
  3   matrix = []
  4   for i in range( 3):
  5       matrix.append( empty_line)
  6   print matrix
  7   
  8   # we change the first item in first line
  9   matrix[0][0] = 1
 10   print matrix  # oops
 11   
 12   # we use the is operator to find if two objects are one
 13   print matrix[0] is matrix[1]
stdout:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
True
Doba běhu: 21.1 ms
If you are not sure whether two variables contain the same object, use the is operator.
Expand/Shrink
Zdroj: (passing1.3.py)
  1   list1 = [1,2,3]
  2   list2 = list1
  3   list3 = [1,2,3]
  4   
  5   print list1 == list2  # True
  6   print list1 is list2  # True
  7   print list1 == list3  # True, tests item by item
  8   print list1 is list3  # False, tests object equality
stdout:
True
True
True
False
Doba běhu: 21.4 ms
Please note that the is operator is useful in this manner only for objects passed by reference. Strings and other types are compared by value.