Python-Ref > Basic usage > Moving objects around > Passing variables to functions
 
 

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

Passing variables to functions

On the previous page we have seen passing by reference in variable assignment. Lets have a look what happens when complex objects are passed as arguments to functions.
Expand/Shrink
Zdroj: (passing2.1.py)
  1   def hungry_sum( xs):
  2       """this function computes the sum of a list in a destructive way"""
  3       res = 0
  4       while len( xs) > 0:
  5           x = xs.pop()
  6           res += x
  7       return res
  8   
  9   
 10   xs = [1,5,10,2,23,45]
 11   print hungry_sum( xs)
 12   print xs
stdout:
86
[]
Doba běhu: 21.1 ms
As demonstrated in the code above, passing by reference takes place also when values are passed into functions. Therefore it is wise not to construct functions that have unexpected side-effects on the input data. As always there are exceptions to this rule.