[Tutor] accessing dynamically created py objects

Kirby Urner urnerk@qwest.net
Wed, 09 Jan 2002 11:21:49 -0800


>
>how can i make this work??
>
>thanks in advance
>mb

To me, it makes more sense to create your N0..Nn as keys
to a dictionary, and then use these to map to values.
If you need multiple values, you could map to lists.  e.g.

  >>> gens = {}
  >>> def maker(n):
         for i in range(n):
           gens["N"+str(i)]=[0,0]


  >>> maker(5)
  >>> gens
  {'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0], 'N4': [0, 0]}

Here each Nn is paired with [0,0] i.e. you could populate either
or both elements.

Now you can go:

  >>> gens['N4'][0] += 1  # increment 0th element of N4 list
  >>> gens
  {'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0],
  'N4': [1, 0]}

It's easier to mass-create distinct entities using some
data structure than to synthesize variables at the
outermost (module) level.

Kirby