use of index (beginner's question)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Apr 28 04:17:32 CEST 2011


On Wed, 27 Apr 2011 17:42:30 -0700, Rusty Scalf wrote:

> Greetings,
> I am just now learning python and am trying to use the index function
> with variables.
> 
> list1 = ['pig', 'horse', 'moose']
> list2 =  ['62327', '49123', '79115']
> a = list2[list1.index('horse')]
> print a
>  >49123
> 
>     -works fine. But
> 
> list1 = ['pig', 'horse', 'moose']
> list2 =  ['62327', '49123', '79115']
> n = 2
> s2 = "list" + `n`
> a = s2[list1.index('horse')]
> print a
> 
>    -does not work


Define "does not work".

What do you expect to happen, and what happens instead? When I try it, 
index works perfectly. You can see that most clearly by extracting out 
the call to index without all the other noise surrounding it. 

>>> list1.index('horse')
1

Works fine.

Whatever your problem is, it has *nothing* to do with index. You could 
remove the call to index completely:

>>> a = s2[1]
>>> print a
i

and get the same result.

If you print s2, you will see your problem:

>>> print s2  # do you expect it to be ['62327', '49123', '79115'] ?
list2


s2 is a string that happens to be the same as the name of the variable 
list2. That's all.


> I'd like to use the index function in a loop updating the file names by
> adding a number to that name with each cycle. But can't get to first
> base.

Don't do it that way. Instead of:

filename1 = 'foo.txt'
filename2 = 'spam.doc'
filename3 = 'image.jpg'

Keep a list of file names:

filenames = ['foo.txt', 'spam.doc', 'image.jpg']

and work with that.



-- 
Steven



More information about the Python-list mailing list