Python Python Basics (2015) Python Data Types Lists

removing something from the list

how do l remove something from the list

2 Answers

Cindy Lea
PRO
Cindy Lea
Pro Student 6,482 Points

Use the remove function. For example:

aList.remove('xyz');

Julian Garcia
Julian Garcia
18,378 Points

Considering a list like a = [1, 2, 3, 4, 2, 'dog', 'cat']

a.remove(2)       remove first 2,  a = [1, 3, 4, 2,  'dog', 'cat']
a.remove('cat'))  remove cat, a= [1, 3, 4, 2,  'dog' ]
a.remove(2)        a= [1, 3, 4,  'dog' ]

you just need to specify the element you want to remove from list but if there are two repeated elements and you want to remove the second one then is better to use del to remove by index, because remove issuing to delete the first occurrence of element from left to right.

if you want to remove by index you can use:

del a[1]     removes first 2,  a= [1, 3, 4, 2,  'dog', 'cat']
del a[-1]    removes the last element,  a= [1, 3, 4, 2,  'dog']
del a[1:3]  delete element 1 and 2 so the result is a= [1, 2,  'dog']