Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "*" mean in Python?

Tags:

python

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.

like image 242
wliao Avatar asked Feb 22 '26 06:02

wliao


1 Answers

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')
>>>
like image 123
pyfunc Avatar answered Feb 24 '26 04:02

pyfunc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!