Increment Variable Name

Grant Edwards grante at visi.com
Wed Jan 23 18:54:13 EST 2008


On 2008-01-23, Diez B. Roggisch <deets at nospam.web.de> wrote:
> David Brochu schrieb:
>> This is probably really trivial but I'm stumped.... :-(
>> 
>> Does anyone know how to increment a variable name?
>> 
>> For example:
>> 
>> I know the length of a list and I want to pass each element of a list to 
>> a unique variable, thus I want to increment variable names. If the list 
>> length = 4, i want to have the following variables: var1, var2, var3, var4.
>> 
>
> Use a dictionary
>
> value_dict = {}
>
> for i, value in values:
>     value_dict["var%i" % i] = value

That assumes that the OPs "list" is actually a list of tumples:

  [(1,firstvalue),(2,secondvalue), (3, thirdvalue), ...]

I'd adjust my thinking (regarding 0/1 based counting) and just
use a list or a tuple:

 var = list(values)
or
 var = tuple(values)

In either case, you now have
 
 var[0], var[1], var[2], var[3], ...


 
If you insist on numbers starting at 1, then a dict would work:

 var = {}
 for i,value in itertools.enumerate(itertools.count(1), values):
    var[i] = value

now you have

  var[1], var[2], var[3], var[4], ...
 


-- 
Grant Edwards                   grante             Yow! I'm continually AMAZED
                                  at               at th'breathtaking effects
                               visi.com            of WIND EROSION!!



More information about the Python-list mailing list