vendredi 5 mai 2017

Python - list index out of range in if statement

I have a list that usually contains items but is sometimes empty.

Three items from the list are added to the database but I run into errors if it's empty, even though I'm using an if statement.

if item_list[0]:
    one = item_list[0]
else:
    one = "Unknown"

if item_list[1]:
    two = item_list[1]
else:
    two = "Unknown"

if item_list[2]:
    three = item_list[2]
else:
    three = "Unknown"

This still raises the list index out of range error if the list is empty. I can't find any other ways in which it could be done, but there must be a better way (I've also read that you should avoid using else statements?)

Aucun commentaire:

Enregistrer un commentaire