Creating variables on the fly...

Joachim Kaeber kaeber at gmd.de
Mon Apr 3 15:24:32 EDT 2000


Hi,

what about this:

def add(*args):
   sum=0
   for arg in args:
     sum=sum+arg
   return sum

add(1,2,3,4)
=> 10

add (1,2,3,4,5,6,7)
=> 28


Matthew Hirsch wrote:
> 
> Hi All,
> 
> Let's say I have four variables:
> 
> a=1
> b=2
> c=3
> d=4
> 
> And I have a function that adds these variables together:
> 
> def add(a,b,c,d):
>    return a+b+c+d
> 
> But now let's say I have twenty variables that I want to add together.
> This function will no longer work.  I would have to rewrite it as
> a+b+c+d+e+f+g+...+(20th letter).  Is there a way to dynamically create a
> variable name?  So that my add function can automatically determine how
> many variable names to create and then add the values together.  In
> other words, I'd ideally like something like:
> 
> def add(number_of_variables):
>    return a+b+c+...+(letter corresponding to number_of_variables)
> 
> Thanks for your help,
> 
> Matt

-- 
Joachim Kaeber (kaeber at gmd.de) (http://imk.gmd.de/~kaeber)
GMD - Forschungszentrum Informationstechnik GmbH
    - German National Research Center for Information Technology
Schloss Birlinghoven                    email: kaeber at gmd.de
D-53757 Sankt Augustin 1, Germany       phone: (+49 2241) 14-2546



More information about the Python-list mailing list