Creating variables on the fly...

William Park parkw at better.net
Sun Apr 2 22:12:29 CEST 2000


On Mon, Apr 03, 2000 at 03:16:03PM -0400, 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

Straightforward approach is 
    def add(*argv):
	<Add each element of tuple 'argv' in a loop>

    sum = add(a, b, c, ...)

Or, you can use dictionary,
    def add(**argv):
	<Add each element of dictionary 'argv' in a loop>

    sum = add(a=a, b=b, ...)
    
--William




More information about the Python-list mailing list