Can't get around "IndexError: list index out of range"

erikcw erikwickstrom at gmail.com
Fri Oct 6 19:57:23 EDT 2006


I ended up using len(sys.argv) > 1 for this particular problem.  But I
think slicing is closer to the tool I was looking for.

I found a.has_key(k) or "k in a" for dictionaries - but haven't found
anything similar for lists.  Does it exist?

I guess my example from php would technically be a dictionary in python
and not a list, it would nice to be able to quickly tell if a list key
existed or not.

Thanks!
Erik


Steve Holden wrote:
> erikwickstrom at gmail.com wrote:
> > Hi all,
> >
> > I'm sorry about the newbie question, but I've been searching all
> > afternoon and can't find the answer!
> >
> > I'm trying to get this bit of code to work without triggering the
> > IndexError.
> >
> > import shutil, os, sys
> >
> > if sys.argv[1] != None:
> >     ver = sys.argv[1]
> > else:
> >     ver = '2.14'
> >
> > Of course, whenever I run it, I get list index out of range.
> >
> > I'm coming from the php world where I can do:
> > if $_GET['var'] != Null {
> >   $ver = $_GET['var'];
> > } else {
> >   $ver = '2.14';
> > }
> >
> > Can anyone tell me how to make this work in python?
> >
> Well all the advice you've had so far seems good, but of course the
> simplest way is just to test the length of the sequence before you try
> to address its second element:
>
> if len(sys.argv) > 1:
>    ver = sys.argv[1]
> else:
>    ver = "2.14"
>
> regards
>   Steve
> --
> Steve Holden       +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd          http://www.holdenweb.com
> Skype: holdenweb       http://holdenweb.blogspot.com
> Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list