List index - why ?

Logan logan at phreaker.nospam
Thu Nov 27 08:16:22 EST 2003


On Thu, 27 Nov 2003 10:48:04 +0100, Kepes Krisztian wrote: 
> The string object have a method named "index", and have a method named
> "find".
> It is good, because many times we need to find anything, and it is
> very long to write this:
> 
> try:
>    i=s.index('a')
> except:
>    i=-1
> if i<>-1: pass
> 
> and not this:
> 
> if (s.find('a')<>-1): pass
> 
> Why don't exists same method in the list object ?
> 
> It is very ugly thing (sorry, but I must say that).
> 
> I must write in every times:
> 
> l=[1,2,3,4]
> try:
>    i=l.index(5)
> except:
>    i=-1
> if i<>-1: pass
> 
> and not this:
> if (l.find(5)<>-1): pass
> 

You can simply use the 'in' operator:

  a = "test"
  b = ['t', 'e', 's', 't']

  if 's' in a: ...
  if 's' in b: ...

'find' and 'index' will give you the position of the first 
occurrence of what you are looking for; but 'find' will return
-1 if what you are looking for is not in the string whereas 'index'
will return a ValueError (s. example below). If you just want to 
test, whether something is in a string or a list, use 'in'.

  's' in a --> True
  's' in b --> True
  a.find('s') -->  2
  b.index('s') --> 2

  'z' in a --> False
  'z' in b --> False
  a.find('z') --> -1
  a.index('z') --> ValueError

HTH, L.


-- 
mailto: logan at phreaker(NoSpam).net





More information about the Python-list mailing list