How Do I...?

Tim Chase python.list at tim.thechases.com
Fri Dec 18 15:03:48 EST 2009


Victor Subervi wrote:
> How do I...?

Well, you start by reading a book on how to program.  You would 
then learn that what you want (in all likelihood) is a 
dictionary/map structure for dynamically created key/value pairs. 
Once you have progressed from your current apprenticeship and 
achieved the rank of third-degree journeyman programmer, the ways 
of dynamic variable creation will avail themselves.

>     i = 0
>     nameNos = []
>     nos = []
>     for option in ourOptions():
>       nameNos.append('optionNo%d' % i)
>       nos.append(i)
>       i += 1
> 
> The idea is that through every iteration of option, I can create a new
> variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0',
> '1' etc to them. Of course that code doesn't work. What would?

As stated above, you want a dictionary where your keys are

   'optionNo%d' % i

and your values are "i".  You can also use the more idiomatic

   for i, option in enumerate(ourOptions()):
     ...

and skip the manual initialization and incrementation of "i".  Or 
even more succinctly, you could pass the above as a generator to 
the dict() initialization.  But that's a level-2 apprentice bit 
of code.  Patience grasshopper.

And as additional weirdness, you don't actually make use of 
"option" in your for-loop...

-tkc






More information about the Python-list mailing list