Join Regular Classroom : Visit ClassroomTech

Remove first n elements in Python List

There are many ways of doing it using methods-

1. pop method – list.pop(index)
2. remove method – list.remove(list[index])
3. del function – del list[index]
4. slicing – list[n:]

Here is an example for you-

# code
# www.codewindow.in

a=[100,111,122,132,144]
b=[10,11,12,13,14]
c=['a','s','d','f']
d=["code","window","repeat"]

n=int(input())

#using pop method
for i in range (n):
    a.pop(0)
print(a)

#using remove method
for i in range (n):
    b.remove(b[0])
print(b)

#using del method
for i in range (n):
    del c[0]
print(c)

#using slicing
d=d[n:]
print(d)

Input:
2

Output:

[122, 132, 144]
[12, 13, 14]
['d', 'f']
['repeat']

Explanation:
Here,
pop(0) pops the first element from the list. The for loop executes the block n times which means the first element is removed every time the list gets updated.
remove(b[0]) removes the element indexed at 0 i.e. the first element. The for loop executes the block n times which means the first element is removed every time the list gets updated.
del c[0] deletes the first element indexed at 0 i.e. the first element. The for loop executes the block n times which means the first element is removed every time the list gets updated.
d[ n:] slices the array from index 2 which is ‘n’ here, leaving the elements from 0 to 1.


Also checkout