Creating variables on the fly...

Matthew Hirsch meh9 at cornell.edu
Mon Apr 3 16:17:17 EDT 2000


I like this solution.  How do I use the apply function in the body to 
call add()?  (I won't know ahead of time how many arguments are going in 
the function).

Thanks,
Matt




In article <38E8EFF0.D71D0415 at gmd.de>, Joachim Kaeber <kaeber at gmd.de> 
wrote:

> 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



More information about the Python-list mailing list