use of index (beginner's question)

Chris Angelico rosuav at gmail.com
Wed Apr 27 20:49:33 EDT 2011


On Thu, Apr 28, 2011 at 10:42 AM, Rusty Scalf <iai-gis at sonic.net> wrote:
> list1 = ['pig', 'horse', 'moose']
> list2 =  ['62327', '49123', '79115']
> n = 2
> s2 = "list" + `n`
> a = s2[list1.index('horse')]
> print a

s2 is a string with the value "list2"; this is not the same as the
variable list2. You could use eval to convert it, but you'd do better
to have a list of lists:

lists = [
 ['pig', 'horse', 'moose']
 ['62327', '49123', '79115']
]

Then you could use:
n = 2
a = lists[n][list1.index('horse')]

If it helps, you can think of this as a two-dimensional array;
technically it's not, though, it's a list that contains other lists.
(Note that you probably don't want to use the word 'list' as a
variable name; it's the name of the type, and is actually a token in
its own right. But 'lists' or something is fine.)

Chris Angelico



More information about the Python-list mailing list