Welcome

21 December 2018

what does * (asterisk) mean in [Python]?

Background

When I was, again, doing some tutorials from Zetcode, I ran into something I don't quite understand.
grid.addWidget(button, *position)
This is a part of the code inside a For Loop.
grid was defined in other parts of the code as a GridLayout( ) object.
button was defined as the new button object to be added into the grid layout in this For Loop.
position is the item in a list of positions in a form of (row, column). e.g. (2,3)

The addWidget( ) method will take arguments widget, row, and column.
QGridLayout.addWidget (self, QWidget, int row, int column, Qt.Alignment alignment = 0)
The thing that I was confused on was why do we have to put an asterisk * in front "position" to make it work.

Answer

(found in a stackoverflow page)

In the function definition of Python, * is an identifier that group or ungroup lists. 

The following example is a function definition that will group args (that is, any other input other than a,b,c, (the first three inputs)) into a list.
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")
If we call this function, the console should print out
a = testa
b = testb
c = testc
('excess', 'another_excess') 

An example of ungrouping lists with * is
def foo(a,b,c,*args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)
This should output
a=testa
b=testb
c=testc
args=('excess',)

While grouping and ungrouping tuples (lists) we can use an asterisk *, grouping and ungrouping dictionaries we can use 2 asterisks **.

No comments:

Post a Comment