lundi 8 juin 2015

Python: How to check the value of a non-existent list element without getting IndexError?

I'm using Python's one-line conditional thus:

x = 'foo' if myList[2] is not None else 'bar'

to assign to x the value of an item at a certain index of a list - if and only if it exists - and a different value if it doesn't.

Here's my challenge: myList can have up to three elements, but won't always have three. So if the index doesn't exist (i.e. if the index in question is 1+ greater than the size of the list), I'll obviously get an IndexError list out of range before the inline conditional can assign the variable:

In [145]: myList = [1,2]

In [146]: x = 'foo' if myList[2] is not None else 'bar'
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-146-29708b8c471e> in <module>()
----> 1 x = 'foo' if myList[2] is not None else 'bar'

IndexError: list index out of range

Checking the length of the list beforehand is not really an option, since I can't know which value I'm interested in is missing (i.e. myList can be missing any or all of three possible values. Knowing that it contains only one, or two, or three elements does not help).

So, long story short: How can I check for a non-existent list item at a certain index, while getting to keep Python's one-line conditional?

Aucun commentaire:

Enregistrer un commentaire