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


Messages In This Thread
extract first and last 5 elements from given list and generate a new list. - by Raj_Kumar - Dec-07-2019, 04:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 443 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 481 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,174 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,106 Jun-12-2023, 05:40 PM
Last Post: snippsat
  Delete strings from a list to create a new only number list Dvdscot 8 1,545 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 921 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Checking if a string contains all or any elements of a list k1llcod3 1 1,108 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  Extract value from a list thesquid 2 863 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,839 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 2,001 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