[Tutor] python $i equivalent ?

Chad Crabtree flaxeater at yahoo.com
Thu Jun 10 10:49:59 EDT 2004

--- Michele Alzetta <michele.alzetta at aliceposta.it>
> 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 ?
Well you are right because the list manipulations
inside the for loop is another namespace or scope, so
any modifications are droped.  This is just alittle
irritating but atleast it's consistent.  Here are two
ways to do the list

Assumption you have a list you need to iterate over
to instantiate the lists properly
for x in alist:

This will take the targelist outside of the for loop
namespace and append to it so you will have these
changes outside of the for loop.

This is a method I use often. (Standard Warning) This
is a destructive way to iterate over a list it uses
the iterator method enumerate() look it up in the docs
for a full description.

alist=range(1,101) #this the original list
for number, value in enumrate(alist):

when this is done the original list will be gone and
in the place of each member will be your class. 
Python is cool in the manner in wich it unpacks these
variables enumerates returns the value and the index
number of each list slice.  This way you can use it to
do usefull stuff.  The old way of doing this was this

for x in range(0,len(alist)):

As as usuall feel free to ask further questions.

Good Luck

Do you Yahoo!?
Friends.  Fun.  Try the all-new Yahoo! Messenger.

More information about the Tutor mailing list