2

I came across with a line in python.

            self.window.resize(*self.winsize)

What does the "*" mean in this line? I haven't seen this in any python tutorial.

3

3 Answers 3

8

One possibility is that self.winsize is list or tuple. The * operator unpacks the arguments out of a list or tuple.

See : http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

Ah: There is an SO discussion on this: Keyword argument in unpacking argument list/dict cases in Python

An example:

>>> def f(a1, b1, c1): print a1
... 
>>> a = [5, 6, 9]
>>> f(*a)
5
>>> 

So unpacks elements out of list or tuple. Element can be anything.

>>> a = [['a', 'b'], 5, 9]
>>> f(*a)
['a', 'b']
>>> 

Another small addition : If a function expects explicit number of arguments then the tuple or list should match the number of elements required.

>>> a = ['arg1', 'arg2', 'arg3', 'arg4']
>>> f(*a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 3 arguments (4 given)
>>> 

To accept multiple arguments without knowing number of arguments:

>>> def f(*args): print args
... 
>>> f(*a)
('arg1', 'arg2', 'arg3', 'arg4')
>>>
2
  • @Falmarri : Thanks a lot! I was not sure and did not want to be sound know all.
    – pyfunc
    Commented Dec 22, 2010 at 5:25
  • 1
    @lyrae: Not at all. It will work with anything as elements of list or tuple. try it out.
    – pyfunc
    Commented Dec 22, 2010 at 5:26
2

Here, self.winsise is a tuple or a list with exactly the same number of elements as the number of arguments self.window.resize expects. If the number is either less or more, an exception will be raised.

That said, we can create functions to accept any number of arguments using similar trick. See this.

0
2

It doesn't have to be a tuple or list, any old (finite) iterable thing will do.

Here is an example passing in a generator expression

>>> def f(*args):
...     print type(args), repr(args)
... 
>>> f(*(x*x for x in range(10)))
<type 'tuple'> (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

Not the answer you're looking for? Browse other questions tagged or ask your own question.