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

3.9k views Asked by At

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).

Update: the reason why I can't assign based on the length of the list is as follows. The list can have a maximum size of 3, and order is important. The values populated will be the result of three separate calls to an API. If all calls to the API succeed, I get a full list, and everything is fine. Yet if only two return a value, the list only contains two items, yet I cannot know which API call has led to the missing item, so assigning variables is pot luck.

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?

2

There are 2 answers

6
Martijn Pieters On BEST ANSWER

Just test if there are enough elements:

x = 'foo' if len(myList) > 2 and myList[2] is not None else 'bar'

It doesn't matter if the first 2 elements are missing or if you have more than 3 elements. What matters is that the list is long enough to have a 3rd element in the first place.

1
Alex Ivanov On

Use try.

#!/usr/bin/python
# -*- coding: utf-8 -*-

L=[1,2,3]

i=0
while i < 10:
    try:
        print L[i]

    except IndexError as e:
        print e, 'L['+str(i)+']'

    i += 1

Output

1
2
3
list index out of range L[3]
list index out of range L[4]
list index out of range L[5]
list index out of range L[6]
list index out of range L[7]
list index out of range L[8]
list index out of range L[9]