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)]



  Saturday, 12 January 2013 at 7:39 pm

Aaron Swartz is perhaps most well known for being a co-founder of Reddit among many other accomplishments including co-author of RSS 1.0 specifications, creator of web.py, and co-found of Demand Progress. Recently he was indicted with federal charges and possibly facing a long term prison sentence. His crime was for downloading around 4 millions academic articles off of JSTOR and planning to distribute them on p2p networks. Aaron Swartz committed suicide on January 11th, 2013 in New York City. He was 26 years old.




-



Search

Categories


Archive