pretty basic: get variable name from list of strings?

Jonathan Hogg jonathan at onegoodidea.com
Tue Jul 30 04:22:39 EDT 2002


On 30/7/2002 4:37, in article oktbkuokccfaimsqs1qd6dcgs84qfommm5 at 4ax.com,
"chris" <chris> wrote:

> thanks for the advice.  i'm definitely new to programming in addition
> to python, so I appreciate the big-picture advice.

In general, whenever you think you need a lot of similar variable names
containing similar things, you probably actually want a single variable
containing a list of things, i.e.:

>>> horse1 = 'tonto'
>>> horse2 = 'silver'
>>> horse3 = 'blackie'
>>> 
>>> horse2
'silver'
>>> 

makes more sense as:

>>> horses = [ 'tonto', 'silver', 'blackie' ]
>>>      
>>> horses[1]
'silver'
>>> 

Elements of a list can be indexed  by their position - note though that
lists are numbered from 0 not 1.

Using collections allows you to do generalised operations across all the
elements of the collection. For instance:

>>> for horse in horses:
...     print 'A horse might be called', horse
... 
A horse might be called tonto
A horse might be called silver
A horse might be called blackie
>>> 

If, on the other hand, you think you want a lot of differently named
variables containing similar things, you probably actually want a
dictionary, i.e.:

>>> tonto = 'white'
>>> silver = 'grey'
>>> blackie = 'black'
>>> 
>>> print 'silver is', silver
silver is grey
>>> 

makes more sense as:

>>> colours = { 'tonto': 'white', 'silver': 'grey', 'blackie': 'black' }
>>> 
>>> print 'silver is', colours['silver']
silver is grey
>>> 

Again, using a collection allows you to do something to/with all of the
elements in a general way:

>>> for horse in colours:
...     print horse, 'is', colours[horse]
... 
tonto is white
blackie is black
silver is grey
>>> 

Note that, in contrast to a list, the order things come out of a dictionary
is not necessarily the order you put them in.

Hope this helps a little. Take comfort that you've picked a good language to
start learning in :-)

-oh-a-horse-is-a-horse-of-course-of-course...-ly y'rs,

Jonathan




More information about the Python-list mailing list