Question on for loop

alex23 wuwei23 at gmail.com
Fri Jan 4 01:47:08 CET 2013


On Jan 4, 6:04 am, subhabangal... at gmail.com wrote:
> but can we do something to assign the variables dynamically I was thinking
> of
> var_series=['var1','var2','var3']
> for var in var_series:
>   for fruit in fruits:
>        print var,fruits

Before trying to do this, write the next bit of code where you _use_
such variables. What do you do if there are no fruits? What do you do
if there are 7000?

You don't want variables to be optional, because otherwise you'll need
to guard every usage with something like:

    if 'var2893' in locals(): ...

Of course, you can also automate this, but why push values into a
dictionary that exists for one purpose if you're not going to use it
that way?

If you need to deal with an unknown number of objects, use a list. If
those objects have a name by which you can refer to them, use a
dictionary.



More information about the Python-list mailing list