List index - why ?

Matt Goodall matt at pollenation.net
Thu Nov 27 06:00:40 EST 2003


Kepes Krisztian wrote:

>Hi !
>
>A.)
>
>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
>  
>
In this example you can use:

 >>> l = [1,2,3,4]
 >>> if 5 not in l:
 >>>     # do something

You can actually do the same for strings

 >>> if 'd' not in 'abc':
 >>>     # do something

which is much more readable than

 >>> if 'abc'.find('d') != -1:
 >>>    # do something

(Note, <> is discouraged. Use != instead.)

>B.)
>
>Same thing is the deleting.
>
>I think, this method is missing from strings, and lists.
>
>Example:
>
>I must write this:
>
>s='abcdef'
>l=[1,2,5,3,4,5]
>
>print s
>s=s[:2]+s[3:]
>print s
>  
>
Python strings are immutable. You can't delete characters, you can only 
build a new string.

>print l
>l[2]=None
>l.remove(None)
>print l
>
>and not this:
>s='abcdef'
>l=[1,2,5,3,4,5]
>s=s.delete(2)
>l.delete(2)
>  
>
And lists are not immutable so you can change them in place.

It's not clear what you're trying to remove from l: the int object with 
value 2 or the item at index 2. Either are possible:

 >>> l.remove(2)
 >>> del l[2]

Cheers, Matt

-- 
Matt Goodall, Pollenation Internet Ltd
w: http://www.pollenation.net
e: matt at pollenation.net
t: +44 (0)113 2252500







More information about the Python-list mailing list