use of index (beginner's question)

R

Rusty Scalf

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

-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

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.

Thank you,

Rusty Scalf
 
S

Steven D'Aprano

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

-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.
1

Works fine.

Whatever your problem is, it has *nothing* to do with index. You could
remove the call to index completely:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top