Mostly Linux & Python syntax notes and hyperlinks.

Thursday, January 23, 2014

python: "splat" operator * to unpack a list to use it as method parameters

I had a long list of parameters to be re-used in different methods. 
if condition1:
    method1( a,b,c,d,e,f,g,h,i,j)
elif condition2:
    method2( a,b,c,d,e,f,g,h,i,j)
I wanted to define the list only once.
 parameter_list=a,b,c,d,e,f,g,h,i,j
I didn't know how to use the values in the method call. If you use it directly, i.e.
method1(parameter_list) <- br="" nope="">
it's only one parameter, instead of the number of parameters in the list.

I found the answer in:
http://stackoverflow.com/questions/4979542/python-use-list-as-function-parameters

Apply the "splat" operator (*) to the parameter list, and it will work.
Here's an example:
>>> def sum(a,b,c):
...   print a+b+c
...
>>> sum(1,2,3)
6
>>> q=1,2,3
>>> sum(q)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: sum() takes exactly 3 arguments (1 given)
>>> sum(*q)
6
 

No comments:

Post a Comment