Asterisk sign in python

Myles myles at geocities.com
Thu Feb 26 17:21:37 EST 2004


Hi Sarmin,

> and then u have something like this:
> func(*param)
[...]
> I just cant figure out what is the asterisk (*) sign for and what is 
> the different between *param and param??

The asterisk is used for multiple parameters, which are passed to
the function as a tuple.

If your function might be called with a varying number of arguments:

myfunc(10)
or
myfunc(10, 20, 30)
or
myfunc(10, "ten", 20, "twenty")

you could write it as:

def myfunc(*param):
    print param

and you would get
>>> myfunc(10)
(10,)
>>> myfunc(10, 20, 30)
(10, 20, 30)
>>> myfunc(10, "ten", 20, "twenty")
(10, 'ten', 20, 'twenty')

If you had defined your function without the 
asterisk, you could only use a single parameter:

def myfunc(param):
    print param

>>> myfunc(10)
10
>>> myfunc(10, 20, 30)

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in -toplevel-
    myfunc(10, 20, 30)
TypeError: myfunc() takes exactly 1 argument (3 given)

You can have non-optional parameters before the asterisk parameter:

def myfunc(required, necessary, *optional):
    print "required", required
    print "necessary", necessary
    print "optional", optional

>>> myfunc(10, 20, 30, 40)
required 10
necessary 20
optional (30, 40)
>>> myfunc(10)

Traceback (most recent call last):
  File "<pyshell#35>", line 1, in -toplevel-
    myfunc(10)
TypeError: myfunc() takes at least 2 arguments (1 given)


Regards, Myles.



More information about the Python-list mailing list