Python assignment loop

George Sakkis george.sakkis at gmail.com
Sun May 20 23:21:52 EDT 2007


On May 20, 10:33 pm, "Silver Rock" <silverfrequ... at gmail.com> wrote:
> i need to do something like this:
>
> ###
> import wx
> x=number
> for i in range(500):
>    "var"+str(i)=ClassXYZ(...,x+i,...)
>
> #.... code
> y=number
> for i in range(y):
>    ClassAAAA(object_called_by_the_string("var"+str(i)),...)
>
> ###
> i can't figure out how to do this, and could not find it on the web.
> c.

Whenever you are tempted to create dynamically variables names, 99% of
the time what you really want is a data structure, typically a dict or
a list. In your example, a list will do:

x=number
xyz_objects = [ClassXYZ(...,x+i,...) for i in xrange(500)]
#.... code
y=number
aaaa_objects = [ClassAAAA(object_called_by_the_string(xyz,...)
                for xyz in xyz_objects[:y]]

If you can't figure out what this does, lookup for "list
comprehensions". By the way, I hope these were shortened examples and
you're not actually using names such as 'ClassAAAA' or 'ClassXYZ' in
your actual code...

George




More information about the Python-list mailing list