Python Forum
extract first and last 5 elements from given list and generate a new list.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
extract first and last 5 elements from given list and generate a new list.
#1
Hi,

Iam very sorry. i have very very basic doubt. i wrote the code and getting error. but i can't understand why error is occurring.

given list: num = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
Required Output = [2,3,4,5,6,12,13,14,15,16]
for i in range(len(num)+1):
    if i<5:
        k.append(num[i])
    elif  i>len(num)-5:
        k.append(num[i])
    else:
        continue
print(k)
Error is:
Error:
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-220-bb56973675c6> in <module> 12 k.append(s[i]) 13 elif i>len(s)-5: ---> 14 k.append(s[i]) 15 else: 16 continue IndexError: list index out of range
Regards
Raj Kumar
Reply
#2
Your for loop is going to high. Note that len(num) is 15, and remember that the index of the first item is 0. So the index of the last item is 14. You range will go from 0 to 15 (one short of len(num) + 1, or just len(num)). So at the end you are trying to get num[15], which is out of range, as the error notes.

You can get this with simple slicing: output = num[:1] + num[-5:].
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 373 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,091 Sep-24-2023, 05:03 AM
Last Post: deanhystad
Question Need help for a python script to extract information from a list of files lephunghien 6 1,033 Jun-12-2023, 05:40 PM
Last Post: snippsat
  Delete strings from a list to create a new only number list Dvdscot 8 1,466 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Checking if a string contains all or any elements of a list k1llcod3 1 1,023 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  Extract value from a list thesquid 2 810 Nov-29-2022, 01:54 PM
Last Post: thesquid
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,714 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 1,899 Aug-24-2022, 05:26 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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