Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Index out of range error
#1
Hi Everyone,
I am trying to create a sublist which uses a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the number 5 (it should not contain the number 5).
I am able to acheive that using the below code but getting Index Error: List index out of range.

def sublist(l):
my_list= []
idx= 0
while l[idx]!= 5:
my_list.append(l[idx])
idx= idx+1
return my_list
p= [3,4,2,43,5,6]
print(sublist(p))
I appreciate any help on this.

Thanks,
Shikha
Reply
#2
First - this code runs ok on my machine if intentation is fixed.

>>> def sublist(l):
...     my_list= []
...     idx= 0
...     while l[idx]!= 5:
...         my_list.append(l[idx])
...         idx= idx+1
...     return my_list
...
>>> p = [3,4,2,43,5,6]
>>> print(sublist(p))
[3, 4, 2, 43]
However, this is very complicated solution. You know the number which should break the original list to sublist. You can get index of that number and make slice:

>>> new = p[:p.index(5)]
>>> new
[3, 4, 2, 43]
If there is no 5 in the list then ValueError will be raised. If there is possibility that it could happen then it should be wrapped into try..except.

EDIT: now I get it. IndexError will be raised when there is no 5 in list. It logical as index is incremented until 5 is encountered.

You should use for loop instead of while:

>>> def sublist(l):
...     my_list = []
...     for el in l:
...         if el == 5:
...             break
...         else:
...             my_list.append(el)
...     return my_list
...
>>> p = [3,4,2,43,6]
>>> sublist(p)
[3, 4, 2, 43, 6]
>>> p = [3,4,2,43,5,6]
>>> sublist(p)
[3, 4, 2, 43]
With index and slicing it could be:

>>> def sublist(l, *, breaker=5):
...     try:
...         return l[:l.index(breaker)]
...     except ValueError:
...         return l[:]                   
...
>>> p = [3,4,2,43,6]
>>> sublist(p)
[3, 4, 2, 43, 6]
>>> p = [3,4,2,43,5, 6]
>>> sublist(p)
[3, 4, 2, 43]
>>> sublist(p, breaker=2):
[3, 4]
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.
Reply
#3
Taking of advantage built-in iter() function and combining it with functools.partial one can extract sublist with unreadable oneliner:

>>> from functools import partial
>>> p = [3, 4, 2, 43, 5, 6]
>>> list(iter(partial(next, iter(p)), 5))
[3, 4, 2, 43]
Slightly more readable as function:

>>> from functools import partial
>>> def sublist(l, *, breaker=5):
...     give_me_next_in_list = partial(next, iter(l))
...     return list(iter(give_me_next_in_list, breaker))
...
>>> sublist([3, 4, 2, 43, 5, 6])
[3, 4, 2, 43]
>>> sublist([3, 4, 2, 43, 6])
[3, 4, 2, 43, 6]
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyscript index error while calling input from html form pyscript_dude 2 938 May-21-2023, 08:17 AM
Last Post: snippsat
  Index error help MRsquared 1 739 May-15-2023, 03:28 PM
Last Post: buran
Thumbs Down I hate "List index out of range" Melen 20 3,161 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,979 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,847 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,280 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,411 May-03-2022, 01:39 PM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,112 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,765 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,239 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020