Join Regular Classroom : Visit ClassroomTech

Remove first instance of element in python

There are many ways of doing it
1. pop method – list.pop()
2. remove method – list.remove(list[index])
3. del function – del list[index]
4. slicing – list[1:]

Example:

# code to understand how to remove first instance of element in python
# www.codewindow.in

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

#using pop method
a.pop(0)
print(a)

#using remove method
b.remove(b[0])
print(b)

#using del method
del c[0]
print(c)

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

Output:

[111, 122, 132, 144]
[11, 12, 13, 14]
['s', 'd', 'f']
["window", "repeat"]

Explanation:
Here, pop(0) pops the first element from the list.
remove(b[0]) removes the element indexed at 0 i.e. the first element.
del c[0] deletes the first element indexed at 0 i.e. the first element.
d[ 1:] slices the array from index 1 leaving the first element at 0.


Follow Us

You Missed

Also Checkout