Python Forum

Full Version: extract first and last 5 elements from given list and generate a new list.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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:].