HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to remove an element from a list by index

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
indexhowfromremoveelementlist

Problem

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

I found list.remove(), but this slowly scans the list for an item by value.

Solution

Use del and specify the index of the element you want to delete:

>>> 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 supports slices:

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


Here is the section from the tutorial.

Code Snippets

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

Context

Stack Overflow Q#627435, score: 2611

Revisions (0)

No revisions yet.