Python-Ref > Basic usage > Functions > Using sequences of arguments as function input
 
 

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

Using sequences of arguments as function input

How to pass arguments to functions when we already have them in a sequence.
We already know how to create functions with variable number of arguments. Sometimes it is also useful to be able to pass a variable number of arguments to a function from a list or a dictionary. The two examples below show how.
Expand/Shrink
Zdroj: (func10-1.py)
  1   # two mandatory and infinit number of optional arguments
  2   def multiply( a, b, *cs):
  3       """this function returns the result of
  4       multiplication of all its arguments"""
  5       ret = a * b
  6       for c in cs:
  7           ret = ret * c
  8       return ret
  9   
 10   print multiply( 1, 2, 3, 4)
 11   numbers = [2,3,1,5,6] # how to feed these to the function?
 12   # this is not very convenient and extensible
 13   print multiply( numbers[0], numbers[1], numbers[2], numbers[3], numbers[4])
 14   # this is better
 15   print multiply( *numbers) # * is used to 'unroll' the list
stdout:
24
180
180
Doba běhu: 20.5 ms
Expand/Shrink
Zdroj: (func10-2.py)
  1   def example( greeting="hello", subject="world"):
  2     print greeting, subject
  3   
  4   example()
  5   example( greeting="goodbye")
  6   # what if we have a dictionary with values
  7   d = {"greeting":"goodbye", "subject":"sanity"}
  8   # not very nice
  9   example( greeting=d['greeting'], subject=d['subject'])
 10   # much nicer
 11   example( **d)
stdout:
hello world
goodbye world
goodbye sanity
goodbye sanity
Doba běhu: 24.6 ms