[Tutor] python $i equivalent ?

Don Arnold darnold02 at sprynet.com
Wed Jun 9 19:09:08 EDT 2004

The standard way of doing this is to store the instances in a dictionary,
then access them by key.

IDLE 1.0.2      
>>> items = ['apple','boy','cantaloupe']
>>> myvars = {}
>>> for item in items:
	myvars[item] = len(item)

You now effectively have three variables named from the items in your list:

>>> print myvars['apple']
>>> print myvars['cantaloupe']
>>> print myvars['boy']

And you can use any legal dictionary key as a variable name, without its
having to be a valid Python identifier:
>>> myvars['not~a~legal~name'] = 42
>>> print myvars['not~a~legal~name']


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Michele Alzetta
Sent: Wednesday, June 09, 2004 4:25 PM
To: Python Tutor
Subject: [Tutor] python $i equivalent ?

Suppose I wanted to create numerous instances of a class 
and name each istance according to an element in a list ?

for element in list:
    element = Class()

doesn't work of course; I need something like the bash '$' 
stuff here

for element in list:
    $element = Class() 

(of course this is neither bash nor python, I know !)

How would this be done ?

Michele Alzetta

Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list