simple problem with lists I am just forgetting

Paul McGuire ptmcg at austin.rr.com
Thu Jul 31 19:05:21 EDT 2008


On Jul 31, 2:51 pm, Alexnb <alexnbr... at gmail.com> wrote:
> Lets say we have this list:
>
> funlist = ['a', 'b', 'c']
>
> and lets say I do this:
>
> if funlist[4]:
>     print funlist[4]
>
> I will get the exception "list index out of range"
>
> How can I test if the list item is empty without getting that exception?

Try using a slice.  Slices are ignorant of list index validity.

funlist = list("abc")  # too lazy to type ['a', 'b', 'c']
if funlist[4:]:
    print funlist[4]

Voila! No exception!

-- Paul



More information about the Python-list mailing list