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

Life of Brian: Conjugate the verb, "to go" !
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
  Get all values of for loop with an index BollerwagenIng 2 143 Aug-09-2019, 07:58 AM
Last Post: BollerwagenIng
  Setting maximum value of Range() in For loop pmt 4 205 Aug-04-2019, 02:38 PM
Last Post: pmt
  random behavriour when handle process termination signal in Python hamzeah 2 96 Jul-31-2019, 07:32 AM
Last Post: hamzeah
  IndexError: string index out of range ? Q_Y 5 348 Jul-05-2019, 07:18 PM
Last Post: noisefloor
  index out of range rwahdan 3 245 Jul-04-2019, 08:11 PM
Last Post: ichabod801
  is there a reverse index? Skaperen 6 305 Jun-14-2019, 11:47 PM
Last Post: Skaperen
  List of dictionaries: use key-value instead of index? dn237 6 378 Jun-03-2019, 05:52 PM
Last Post: Yoriz
  Preventing: IndexError: list index out of range PappaBear 1 387 Jun-03-2019, 05:50 PM
Last Post: SheeppOSU
  getting index ThinleyJimmyDorji 2 186 May-24-2019, 05:11 PM
Last Post: buran
  json.load causing IndexError: list index out of range WallyZ 5 339 May-20-2019, 01:11 PM
Last Post: WallyZ

Forum Jump:


Users browsing this thread: 1 Guest(s)