Learn the coding skills for your next job

Complete Guide to Removing Elements From Lists in Python

While lists aren’t the most efficient data structure if you’ll be doing lots of deleting from the middle, there are definitely good ways to accomplish the task. The built-in remove() method should be your first option. Let’s go over some examples.

Remove element in Python list by value

primes = [2, 3, 5, 5, 7, 11] primes.remove(5) print(primes) # [2, 3, 5, 7, 11] primes.remove(5) # [2, 3, 7, 11] primes.remove(5) # careful, this will throw an error # ValueError: list.remove(x): x not in list
Code language: Python (python)

If you want to safely remove items, and you aren’t sure if they exist in the list or not, you can either catch the error:

try: primes.remove(5) except Exception as e: print("not in list")
Code language: Python (python)

Or, you can check for existence first:

if 5 in primes: primes.remove(5)
Code language: Python (python)

Learn Python, get hired

Python has been growing in popularity for over 20 years, and today is used by tens of thousands of companies to deliver reliable software. If you are interested in a career in Python get started by writing real code with us.

Remove an element in Python list by index

The del statement is a built-in keyword that allows you to remove items from lists. The simplest example deletes the item at a given index.

primes = [2, 3, 5, 5, 7, 11] # delete the second item del primes[1] print(primes) # [2, 5, 5, 7, 11]
Code language: Python (python)

Again, you need to be careful. If the index doesn’t exist an error will be raised.

primes = [2, 3, 5, 5, 7, 11] # delete the eleventh item del primes[10]
Code language: Python (python)

IndexError: list assignment index out of range

if len(primes) >= 10: del primes[10]
Code language: Python (python)

Remove multiple of items from a python list

primes = [2, 3, 5, 5, 7, 11] # deleting items from 2nd to 4th del primes[1:4] print(primes) # [2, 7, 11]
Code language: Python (python)

Remove item by index and return it

The .pop() method removes an item from a list by index and returns that item.

primes = [2, 3, 5, 7] # pop the second element popped = primes.pop(1) print("popped:", popped) # 3 print("list:", primes) # [2, 5, 7]
Code language: PHP (php)

If you don’t pass an index parameter to pop() it will default to -1 and remove the last element from the list. Just like the other methods, if you pass in a number too large, you’ll get the following error.

IndexError: pop index out of range

Trying to find your next programming job?

If you are a self-taught developer having trouble finding your first programming job, we've got your back! We have the learning resources and tight-knit dev community that you need to land the coding job you've been looking for. To get started, create a free account and join our Discord community.

Have questions or feedback?

If we've made a mistake in the article, please let us know so we can get it corrected!