Why does x,y = zip(*zip(a,b)) work in Python?

The asterisk in Python is documented in the Python tutorial, under Unpacking Argument Lists.


The asterisk performs apply (as it's known in Lisp and Scheme). Basically, it takes your list, and calls the function with that list's contents as arguments.


It's also useful for multiple args:

def foo(*args):
  print args

foo(1, 2, 3) # (1, 2, 3)

# also legal
t = (1, 2, 3)
foo(*t) # (1, 2, 3)

And, you can use double asterisk for keyword arguments and dictionaries:

def foo(**kwargs):
   print kwargs

foo(a=1, b=2) # {'a': 1, 'b': 2}

# also legal
d = {"a": 1, "b": 2}
foo(**d) # {'a': 1, 'b': 2}

And of course, you can combine these:

def foo(*args, **kwargs):
   print args, kwargs

foo(1, 2, a=3, b=4) # (1, 2) {'a': 3, 'b': 4}

Pretty neat and useful stuff.

Tags:

Python