Python Forum

Full Version: catching / handle index out of range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Guys,

Back again, fiddling with an 'index out of range' thingy. To my (limited) knowledge this is how I would do it.

Your thoughts?
a = [1,2,3]
b = [1]
c = [1,4,5,6]
d = [1,2,3]

e = [a,b,c,d]
index_needed = 2
output = [item[index_needed] for item in e if len(item) > index_needed]

print(output)
# outputs 3, 5, 3
Is it output you expected or there is problem with that?

There might be times when you need to get some value in cases where index is out of range. To achieve that you don't filter out indexes which are out of range but with conditional expression you return appropriate value:

>>> index_needed = 3
>>> e = [[1, 2], [1, 2, 3, 4], [1], [1, 2, 3, 4, 5]]
>>> [item[index_needed] if len(item) > index_needed else None for item in e]
[None, 4, None, 4]
Hmm I thought I was satisfied with my setup, but looking at your suggestion: including a None and thus keeping the list length the same might be better actually. And perhaps better in terms of a clear output.

Good one!
you can take advantage of itertools.zip_longest()

from itertools import zip_longest

a = [1,2,3]
b = [1]
c = [1,4,5,6]
d = [1,2,3]
 
index_needed = 2
combined = list(zip_longest(a,b,c,d))
try:
    print(combined[index_needed])
except IndexError:
    print(f'There is no element with index {index_needed}')