Creating variables on the fly...

bragib at my-deja.com bragib at my-deja.com
Tue Apr 4 01:52:54 CEST 2000


Using Joachims approach you would

use apply(add, (1,2,3,4,....,n))

or if you were for example adding these variables to a list
or a tuple you could have.
list = [1,2,3,4]
tuple = (1,2,3,4)
apply(add,list)   --> returns 10
apply(add, tuple) --> returns 10


Bragi



In article <meh9-32FDF8.16171703042000 at news.cit.cornell.edu>,
Matthew Hirsch <meh9 at cornell.edu> wrote:
> 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
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list