use of index (beginner's question)

Thomas 'PointedEars' Lahn PointedEars at web.de
Wed Apr 27 21:23:51 EDT 2011


Chris Angelico wrote:

> Rusty Scalf wrote:
>> list1 = ['pig', 'horse', 'moose']
>> list2 =  ['62327', '49123', '79115']
>> n = 2
>> s2 = "list" + `n`

I would prefer the clearer

  s2 = "list" + str(n)

or

  s2 = "list%s" % 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']
> ]

You forgot a comma after the first `]', to separate the list elements.
A way to reuse the existing code is

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

That would throw an IndexError exception, though, since list indexes are
0-based, and this list has only two items (so the highest index is 1, not 
2).

But even if this was fixed, this could still throw a ValueError exception
if there was no 'horse' in `list1'.  While you could catch that –

  needle = 'horse'
  try:
      a = lists[n][list1.index(needle)]
  except ValueError:
      a = 'N/A'

– perhaps a better way to store this data is a dictionary:

  data = {
      'pig':   '62327',
      'horse': '49123',
      'moose': '79115'
  }

  print data.get('horse')
  print data.get('cow')
  print data.get('cow', 'N/A')

Such a dictionary can be built from the existing lists as well:

  data = dict(zip(list1, list2))
  print data
  print data.get('horse', 'N/A')


HTH
-- 
PointedEars



More information about the Python-list mailing list