Shortcut to initialize variables

Kent Johnson kent37 at tds.net
Fri Jun 17 14:42:51 EDT 2005


Andrew wrote:
> Newb here... For one of my programs I want to initialize a variable for
> each letter of the alphabet. For example, a,b,c = 0,0,0. I don't think
> this works, but I'm wondering if I can do something similar to this:
> 
> from string import ascii_lowercase
> 
> class Blah:
>     def __init__(self):
>         for letter in ascii_lowercase:
>             setattr(self,letter,0)
> 
> Is there a way I can do something like this without using classes?

This is a very common request on this list. The usual advice is to use a dictionary rather than defining variables, e.g.
letters = {}
for letter in ascii_lowercase:
  letters[letter] = 0


But I'm becoming curious about why this is so commonly requested. What is your background that you (and others) would think of this as a solution? Is there a language where it is easy to do this sort of thing, and where the resulting variables are easily used?

Thanks,
Kent



More information about the Python-list mailing list