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
  Compile list of dictianories out of another list of dictianories by certain keys CatorCanulis 10 475 Jun-10-2021, 08:35 PM
Last Post: perfringo
  I cannot delete and the elements from the list quest 4 446 May-11-2021, 12:01 PM
Last Post: perfringo
  List of lists - merge sublists with common elements medatib531 1 328 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Find Common Elements in 2 list quest 4 444 Apr-14-2021, 03:57 PM
Last Post: quest
  Order a list with successive permutations based on another list yvrob 3 464 Mar-19-2021, 08:20 AM
Last Post: supuflounder
  Saving list in a list quest_ 3 619 Mar-10-2021, 09:58 AM
Last Post: quest_
Star Convert Bytearray into List using list() Shlok 2 381 Feb-18-2021, 10:44 AM
Last Post: deanhystad
  Sorting Elements via parameters pointing to those elements. rpalmer 3 508 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  Group List Elements according to the Input with the order of binary combination quest_ 19 1,139 Jan-28-2021, 03:36 AM
Last Post: bowlofred
  Adding List Element if Second part of the List Elements are the Same quest_ 3 521 Nov-25-2020, 04:33 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

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