unpack operator in Python

In Python, the * (asterisk) character is not only used for multiplication and replication, but also for unpacking. There does not seem to be any name for this kind of * operator and thus searching for it online is difficult. But, it is commonly called as the unpack or splat operator in this role.

Applying * on any iterable object, by placing it to the left of the object, produces the individual elements of the iterable.

I imagine this operator as shattering the container that holds the items together, so they are now free and individual. The look of the asterisk character helps bolster this imagination.

def foo( x, y, z ):
    print( "First is ", x, " then ", y, " lastly ", z )

a = [ 1, 50, 99 ]

foo( a )
# TypeError: foo() takes exactly 3 arguments (1 given)

foo( *a )
# First is 1 then 50 lastly 99

b = [ [55,66,77], 88, 99 ]
foo( *b )
# First is [55,66,77] then 88 lastly 99

For more info, see More Control Flow Tools.

Tried with: Python 3.2.2

About these ads

One thought on “unpack operator in Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s