How to remove an element from a list by index

Submitted 4 years, 6 months ago
Ticket #249
Views 369
Language/Framework Python
Priority Low
Status Closed

How do I remove an element from a list by index in Python?

I found the list.remove method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.

Submitted on Oct 19, 20
add a comment

2 Answers

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del a[-1]#index number of the element in the list
print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Submitted 4 years, 6 months ago


Verified

Specify the index of the element you want to delete & Use del

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Also you can use slices:

>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]

For more check the link...

https://docs.python.org/3/tutorial/datastructures.html#the-del-statement

Submitted 4 years, 6 months ago


Latest Blogs