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.

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:
    elif  i>len(num)-5:
Error is:
--------------------------------------------------------------------------- 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
Raj Kumar
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 -
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extracting Elements From A Website List knight2000 2 221 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 232 Jul-11-2021, 09:58 AM
Last Post: perfringo
  Compile list of dictianories out of another list of dictianories by certain keys CatorCanulis 10 652 Jun-10-2021, 08:35 PM
Last Post: perfringo
  I cannot delete and the elements from the list quest 4 625 May-11-2021, 12:01 PM
Last Post: perfringo
  List of lists - merge sublists with common elements medatib531 1 539 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Find Common Elements in 2 list quest 4 620 Apr-14-2021, 03:57 PM
Last Post: quest
  Order a list with successive permutations based on another list yvrob 3 627 Mar-19-2021, 08:20 AM
Last Post: supuflounder
  Saving list in a list quest_ 3 748 Mar-10-2021, 09:58 AM
Last Post: quest_
Star Convert Bytearray into List using list() Shlok 2 514 Feb-18-2021, 10:44 AM
Last Post: deanhystad
  Sorting Elements via parameters pointing to those elements. rpalmer 3 643 Feb-10-2021, 04:53 PM
Last Post: rpalmer

Forum Jump:

User Panel Messages

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