Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

unpack operator in Python

📅 2012-Apr-25 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ python, splat operator, unpack operator ⬩ 📚 Archive

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 * operator and ** operator. So, searching for information on it online can sometimes be difficult. But, they are commonly called as the unpack or splat operator in this role.

* operator

Applying * on any iterable object, by placing it to the left of the object, produces the individual elements of the iterable. If applied on a list-like iterable, it produces the elements of the list in the order they appear in the list. If applied on a dict-like object, it produces the keys of the dict in the order you would get as if you iterated the dict.

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

d = {"y": 23, "z": 56, "x": 15}

foo(*d)
# This passes in the keys of the dict
# First is z then x lastly y

** operator

Applying ** on any dict-like object, by placing it to the left of the object, produces the individual key-value pairs of the iterable. The order of the key-value pairs produced is in the order you would get as if you iterated the dict.

This ** operator makes it easy to pass a dictionary to a function that has keyword arguments. Just make sure that the number of keys and the name of the keys in the dict exactly match the number and names of the function parameters. If the number of keys is less or more than in the function parameters or if some keys do not match the function parameter names, then the function call fails.

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

d = {"y": 23, "z": 56, "x": 15}

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

foo(*d)
# Works, but not what you wanted
# First is z then x lastly y

foo(**d)
# First is 15 then 23 lastly 56

For more info, see More Control Flow Tools.

Tried with: Python 3.5.2


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧