Problem with Lists & Index command

Doug Hellmann doughellmann at mindspring.com
Fri Jun 11 17:44:47 EDT 1999


> import string
> 
> entry   = 'ABCD'
> 
> tcmlist = [('EFGHI',1),('JKLMN',2),('ABCD',3)]
> found   = 0
> entry   = string.upper(string.strip(entry))
> 
> try:
>         found = tcmlist.index (entry)
>         tcmlist[found][1] = tcmlist[found][1] + 1
>         print 'found'
> except ValueError:
>         tcmlist.append (entry,1)
>         print 'Sorry could not find it'
> else:
>         pass
> 
> print tcmlist
> 
> I don't see anything that looks wrong, and getting
> no syntax errors, but....
> 
> It appears that INDEX doesn't work on a multiple
> dimension list????

Using index() on tcmlist is only going to search through the values in
tcmlist.  It won't look inside the tuples that tcmlist contains.  So,
you either have to construct a tuple to pass to index, or use a
dictionary instead of a list:

tcmvalues = { 'EFGHI':1,
              'JKLMN':2,
              'ABCD':3,
            }
entry = 'ABCD'
try:
    found = tcmvalues[ entry ]
except KeyError:
    tcmvalues[ entry ] = 1
else:
    pass

This will be much faster than a list lookup anyway, so if you're trying
to count occurances of entries or something similar you should use the
dictionary.

Doug




More information about the Python-list mailing list