Tuesday, 22 January 2013 at 12:47 pm

The star (*) symbol can be used before a collection object in python to mark it for unpacking when passing to a function. For example:

def doSomething(x, y, z):
return x + y + z

data = [1,2,3]

#Your data is in a list and you want to use doSomething on it.
#The annoying way would be to do this:
doSomething(data[0],data[1],data[2])

#Using star notation
doSomething(*data) 

The star notation before the 'data' variable unpacks the array into 3 separate arguments for the function to process. 

Similarly, you can use a double star (**) notation to unpack values of a dictionary:

dataDict = {'a':1,'b':2,'c':3}
doSomething(**dataDict) 

You can also write a function with star notation argument list to accept a variable number of arguments:

def doAnything(*myValues):
return sum(myValues)

doAnything(1,2,3,4) #return 10
doAnything(1,2) #return 3
doAnything(1) #return 1 

An useful example of the star notation is for transposing tables (make rows into columns and columns into rows):

#data of two rows and 4 columns
#1 2 3 4
#5 6 7 8
data = [(1,2,3,4),(5,6,7,8)]

transposedData = zip(*data)
#transposedData = [(1, 5), (2, 6), (3, 7), (4, 8)]







Search

Categories


Archive