How to remove an element from a list by index

Question:

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.

Asked By: Joan Venge

||

Answers:

You probably want pop:

a = ['a', 'b', 'c', 'd']
a.pop(1)

# now a is ['a', 'c', 'd']

By default, pop without any arguments removes the last item:

a = ['a', 'b', 'c', 'd']
a.pop()

# now a is ['a', 'b', 'c']
Answered By: Jarret Hardie

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.

Answered By: unbeknown

pop is also useful to remove and keep an item from a list. Where del actually trashes the item.

>>> x = [1, 2, 3, 4]

>>> p = x.pop(1)
>>> p
    2
Answered By: boatcoder

Like others mentioned pop and del are the efficient ways to remove an item of given index. Yet just for the sake of completion (since the same thing can be done via many ways in Python):

Using slices (this does not do in place removal of item from original list):

(Also this will be the least efficient method when working with Python list, but this could be useful (but not efficient, I reiterate) when working with user defined objects that do not support pop, yet do define a __getitem__ ):

>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index

>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]

Note: Please note that this method does not modify the list in place like pop and del. It instead makes two copies of lists (one from the start until the index but without it (a[:index]) and one after the index till the last element (a[index+1:])) and creates a new list object by adding both. This is then reassigned to the list variable (a). The old list object is hence dereferenced and hence garbage collected (provided the original list object is not referenced by any variable other than a).

This makes this method very inefficient and it can also produce undesirable side effects (especially when other variables point to the original list object which remains un-modified).

Thanks to @MarkDickinson for pointing this out …

This Stack Overflow answer explains the concept of slicing.

Also note that this works only with positive indices.

While using with objects, the __getitem__ method must have been defined and more importantly the __add__ method must have been defined to return an object containing items from both the operands.

In essence, this works with any object whose class definition is like:

class foo(object):
    def __init__(self, items):
        self.items = items

    def __getitem__(self, index):
        return foo(self.items[index])

    def __add__(self, right):
        return foo( self.items + right.items )

This works with list which defines __getitem__ and __add__ methods.

Comparison of the three ways in terms of efficiency:

Assume the following is predefined:

a = range(10)
index = 3

The del object[index] method:

By far the most efficient method. It works will all objects that define a __del__ method.

The disassembly is as follows:

Code:

def del_method():
    global a
    global index
    del a[index]

Disassembly:

 10    0 LOAD_GLOBAL     0 (a)
       3 LOAD_GLOBAL     1 (index)
       6 DELETE_SUBSCR   # This is the line that deletes the item
       7 LOAD_CONST      0 (None)
      10 RETURN_VALUE
None

pop method:

It is less efficient than the del method and is used when you need to get the deleted item.

Code:

def pop_method():
    global a
    global index
    a.pop(index)

Disassembly:

 17     0 LOAD_GLOBAL     0 (a)
        3 LOAD_ATTR       1 (pop)
        6 LOAD_GLOBAL     2 (index)
        9 CALL_FUNCTION   1
       12 POP_TOP
       13 LOAD_CONST      0 (None)
       16 RETURN_VALUE

The slice and add method.

The least efficient.

Code:

def slice_method():
    global a
    global index
    a = a[:index] + a[index+1:]

Disassembly:

 24     0 LOAD_GLOBAL    0 (a)
        3 LOAD_GLOBAL    1 (index)
        6 SLICE+2
        7 LOAD_GLOBAL    0 (a)
       10 LOAD_GLOBAL    1 (index)
       13 LOAD_CONST     1 (1)
       16 BINARY_ADD
       17 SLICE+1
       18 BINARY_ADD
       19 STORE_GLOBAL   0 (a)
       22 LOAD_CONST     0 (None)
       25 RETURN_VALUE
None

Note: In all three disassembles ignore the last two lines which basically are return None. Also the first two lines are loading the global values a and index.

Answered By: Raghav RV

Generally, I am using the following method:

>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
Answered By: Mayur Koshti

One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.

For example, starting with the list shown, one can remove its last element with del as a slice, and then one can remove the last element from the result using pop.

>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]
Answered By: pyman

As previously mentioned, best practice is del(); or pop() if you need to know the value.

An alternate solution is to re-stack only those elements you want:

    a = ['a', 'b', 'c', 'd'] 

    def remove_element(list_,index_):
        clipboard = []
        for i in range(len(list_)):
            if i is not index_:
                clipboard.append(list_[i])
        return clipboard

    print(remove_element(a,2))

    >> ['a', 'b', 'd']

eta: hmm… will not work on negative index values, will ponder and update

I suppose

if index_<0:index_=len(list_)+index_

would patch it… but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a ‘proper’ way to do this with append() / list comprehension.

pondering

Answered By: litepresence

You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.

>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
 3
>>> a
[1, 4, 5]
>>> 
Answered By: Aashutosh jha

It doesn’t sound like you’re working with a list of lists, so I’ll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it’s “-1”

>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']
Answered By: Mo Ali

You could just search for the item you want to delete. It is really simple.
Example:

    letters = ["a", "b", "c", "d", "e"]
    letters.remove(letters[1])
    print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)

Output: a c d e

Answered By: SollyBunny

Use the following code to remove element from the list:

list = [1, 2, 3, 4]
list.remove(1)
print(list)

output = [2, 3, 4]

If you want to remove index element data from the list use:

list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
Answered By: Jitesh Mohite

Use the del statement:

del listName[-N]

For example, if you want to remove the last 3 items, your code should be:

del listName[-3:]

For example, if you want to remove the last 8 items, your code should be:

del listName[-8:]
Answered By: lloydyu24

This depends on what you want to do.

If you want to return the element you removed, use pop():

>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]

However, if you just want to delete an element, use del:

>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]

Additionally, del allows you to use slices (e.g. del[2:]).

Answered By: Neil

l – list of values; we have to remove indexes from inds2rem list.

l = range(20)
inds2rem = [2,5,1,7]
map(lambda x: l.pop(x), sorted(inds2rem, key = lambda x:-x))

>>> l
[0, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Answered By: Jo Ja

Yet another way to remove an element(s) from a list by index.

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

# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]

# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]

a[x:y] points to the elements from index x to y-1. When we declare that portion of the list as an empty list ([]), those elements are removed.

If you want to remove elements at specific positions in a list, like the 2nd, 3rd and 7th elements, you can’t use

del my_list[2]
del my_list[3]
del my_list[7]

Since after you delete the second element, the third element you delete actually is the fourth element in the original list. You can filter the 2nd, 3rd and 7th elements in the original list and get a new list, like below:

new_list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]
Answered By: xiaojia zhang

Or if multiple indexes should be removed:

print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])

Of course then could also do:

print([v for i,v in enumerate(your_list) if i != unwanted_index])
Answered By: U12-Forward

It has already been mentioned how to remove a single element from a list and which advantages the different methods have. Note, however, that removing multiple elements has some potential for errors:

>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
...     del l[i]
... 
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]

Elements 3 and 8 (not 3 and 7) of the original list have been removed (as the list was shortened during the loop), which might not have been the intention. If you want to safely remove multiple indices you should instead delete the elements with highest index first, e.g. like this:

>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
...     del l[i]
... 
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]
Answered By: nspo

Pretty sure this is what you want. You use index to get the index inside the array of the number two and then del, as other users pointed out.

myList = [3, 5, 7, 2, 100, 76]

del myList[myList.index(2):] #delets from the index of 2 to the end of the array
    
print(myList)

>>>[3, 5, 7]

Answered By: noel puig

Python – Remove elements at Indices in List

Given List, remove all the elements present in the indices list in Python.

Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] 
Output : [5, 6, 7, 2, 10] 
Explanation : 3, 6, and 1 has been removed.

Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] 
Output : [5, 6, 7, 8, 1, 2, 10] 
Explanation : 3 has been removed.  

In this post, I’ll cover how to Remove items at a specific index from Python List, and cover different methods that are listed below:

  • Remove an item by index and get its value using pop()
  • Remove items by index or slice using del()
  • Remove items at a specific index using enumerate() + loop
  • Remove items at a specific index using enumerate() + list comprehension

Method 1: Remove an item by index and get its value using pop()

In this example, we will use the pop method to remove the element from the list, here in the pop we will pass the index value to remove the element at that position.

test_list = [5, 6, 3, 7, 8, 1, 2, 10]
 
test_list.pop(1)
print(test_list)

Output:

[5, 3, 7, 8, 1, 2, 10]

Method 2: Remove items by index or slice using del()

In this example, we will use the del keyword to delete the specific elements present in the list. Here we will remove multiple items from the list by index. Please note that we need to sort the indices in reversed order to ensure that the shift of indices induced by the deletion of elements at lower indices won’t invalidate the index specifications of elements at larger indices.

test_list = [5, 6, 3, 7, 8, 1, 2, 10, 5]
indices=[3,7]
 
for i in sorted(indices, reverse=True):
    del test_list[i]
     
print(test_list)

Output:

[5, 6, 3, 8, 1, 2, 5]

Method 3: Remove items at a specific index using enumerate() + loop

In this, we iterate for all the elements, and if the index is present in the list, then that index element is omitted from the result list.

test_list = [5, 6, 3, 7, 8, 1, 2, 10]

print("The original list is : " + str(test_list))


idx_list = [2, 4, 5, 7]
 
res = []
for idx, ele in enumerate(test_list):
     
    # checking if element not present in index list
    if idx not in idx_list:
        res.append(ele)
 

print("Filtered List after removal : " + str(res))

Output:

The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]

Method 4: Remove items at a specific index using enumerate() + list comprehension

In this, we perform the task of iteration using list comprehension in a compact way, the rest of the methods are similar to the above.

test_list = [5, 6, 3, 7, 8, 1, 2, 10]

print("The original list is : " + str(test_list))

idx_list = [2, 4, 5, 7]
 
# one-liner to test for element in index list
res = [ele for idx, ele in enumerate(test_list) if idx not in idx_list]

print("Filtered List after removal : " + str(res))

Output:

The original list is : [5, 6, 3, 7, 8, 1, 2, 10]
Filtered List after removal : [5, 6, 7, 2]
Answered By: Javad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.