tags:

views:

279

answers:

3

OK I love Python's zip() function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of zip(), think "I used to know how to do that", then google python unzip, then remember that one uses this magical * to unzip a zipped list of tuples. Like this:

x = [1,2,3]
y = [4,5,6]
zipped = zip(x,y)
unzipped_x, unzipped_y = zip(*zipped)
unzipped_x
    Out[30]: (1, 2, 3)
unzipped_y
    Out[31]: (4, 5, 6)

What on earth is going on? What is that magical asterisk doing? Where else can it be applied and what other amazing awesome things in Python are so mysterious and hard to google?

+3  A: 

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.

Chris Jester-Young
Python2 series still has an `apply` function, but i don't think there are any use cases that can't be covered by `*`. I believe it has been removed from Python3
gnibbler
@gnibbler: Confirmed. `apply` is listed at http://www.python.org/dev/peps/pep-0361/ under the heading `Warnings for features removed in Py3k:`
MatrixFrog
Apply only exists because the asterisk was added later.
DasIch
+7  A: 

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

Daniel Stutzbach
wow it's as simple as that! Awesome. Thanks so much!
Mike Dewar
A: 

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.

bcherry
awesome. I wonder if there's any other programming language that could make me this happy. I wonder if I should worry that learning new bits of Python should make me this happy. Or maybe I should learn to stop worrying and love the Python!
Mike Dewar