Python Forum
catching / handle index out of range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: catching / handle index out of range (/thread-15867.html)



catching / handle index out of range - 3Pinter - Feb-04-2019

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



RE: catching / handle index out of range - perfringo - Feb-04-2019

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]



RE: catching / handle index out of range - 3Pinter - Feb-04-2019

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!


RE: catching / handle index out of range - buran - Feb-04-2019

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}')