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')
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

@Falmarri : Thanks a lot! I was not sure and did not want to be sound know all.
@lyrae: Not at all. It will work with anything as elements of list or tuple. try it out.
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.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.