Did you know about Python?

Posted on Wed, 2012-02-22 in coding

Well this is so neat, that I have to share it here. :) So today I learned something fancy about python. Some more syntactic sugar. Oh I know why I code most of my stuff in python. So let's assume we define a function like this:

>>> def func(a, b, c):
...     print(a, b, c)

And we have a list of arguments (for whatever reason), which we like to pass to the function.

>>> alist = [1, 2, 3]
>>> func(alist[0], alist[1], alist[2])
1 2 3

Well this is annoying, but fortunately python has some syntactic sugar :)

>>> func(*alist)
1 2 3

The list has to contain exactly the number of arguments.

This looks similar to the definition of function with a variable number of parameters:

>>> def func(a, b, c, *args):
...     print(a, b, c, args)


Small Update: this also works with dicts!

>>> def func(a=-1, b=-2, c=-3):
...     print(a, b, c)
>>> d = {"a": 1, "b": 2, "c": 3}
>>> func(**d)
1 2 3

Neat isn't it?