Checking whether list element exists
mensanator at aol.com
mensanator at aol.com
Sat Apr 7 11:52:35 EDT 2007
On Apr 7, 10:37�am, Wojciech Mula
<wojciech_m... at poczta.null.onet.pl.invalid> wrote:
> Rehceb Rotkiv wrote:
> > I want to check whether, for example, the element myList[-3] exists. So
> > far I did it like this:
>
> > index = -3
> > if len(myList) >= abs(index):
> > print myList[index]
>
> IMHO it is good way.
>
> > Another idea I had was to (ab-?)use the try...except structure:
>
> > index = -3
> > try:
> > print myList[index]
> > except:
> > print "Does not exist!"
>
> In general case it won't work, because lists accept negative indexes:http://docs.python.org/lib/typesseq.html, 3rd note.
Why? What does negative indexes have to do with it?
>>> a = [1,2]
>>> index = -3
>>> try:
print a[index]
except:
print 'does not exist'
does not exist
>
> w.
More information about the Python-list
mailing list