Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 catching / handle index out of range
#1
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
Quote
#2
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]
3Pinter likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote
#3
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!
Quote
#4
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}')
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  IndexError: List index out of range issue Adem 1 321 Nov-01-2019, 10:47 PM
Last Post: ichabod801
  IndexError: list index out of range bug? CaptainCsaba 4 316 Oct-18-2019, 12:38 PM
Last Post: CaptainCsaba
  MAWS.py PRGM:IndexError: list index out of range bcramer 0 151 Aug-28-2019, 04:45 PM
Last Post: bcramer
  IndexError: string index out of range ? Q_Y 5 910 Jul-05-2019, 07:18 PM
Last Post: noisefloor
  index out of range rwahdan 3 563 Jul-04-2019, 08:11 PM
Last Post: ichabod801
  Preventing: IndexError: list index out of range PappaBear 1 2,526 Jun-03-2019, 05:50 PM
Last Post: SheeppOSU
  json.load causing IndexError: list index out of range WallyZ 5 778 May-20-2019, 01:11 PM
Last Post: WallyZ
  Catching Errors Alienspecimen 1 269 May-18-2019, 11:07 PM
Last Post: Larz60+
  IndexError: list assignment index out of range Apretext 3 1,036 Apr-25-2019, 09:29 PM
Last Post: Yoriz
  tuple index out of range delta1071 3 1,832 Apr-11-2019, 07:15 AM
Last Post: snippsat

Forum Jump:


Users browsing this thread: 1 Guest(s)