Removing an Element from a List in Python

To remove a value from a list, you can use the remove method or the pop method.

The remove Method

list_name.remove(value)

If the element doesn't exist in the list, the remove method will return an error.

The pop Method

list_name.pop(index)

The pop method uses the index of the list as a parameter instead of the value.

If the index is greater than the length of the list, the pop method will raise an error.

Additionally, unlike remove, the pop method returns the removed element.

The remove Method

Given the following list:

year = [2010, 2011, 2012, 2013]

To delete the first element, you would type:

year.remove(2010)

After the change, the list becomes:

[2011, 2012, 2013]

The pop Method

Given the following list:

year = [2010, 2011, 2012, 2013]

To remove and return the first element, you would type:

year.pop(0)

After the change, the list becomes:

[2011, 2012, 2013]

How to Remove Multiple Elements

To remove two or more contiguous elements from a list, you can use slicing.

You specify a range where the first element is included and the second element is excluded:

list[start_included:end_excluded] = []

This assigns the specified range to an empty list [].

A Practical Example

Given the following list:

year = [2010, 2011, 2012, 2013]

To remove the first two elements, you would type:

year[0:2] = []

After the change, the list becomes:

[2012, 2013]

Now, to remove the last element, you would type:

year[-1:] = []

The final list becomes:

[2012]

And so on.

The del Statement

Another way to remove elements from a list is by using the del statement:

del list_name[index]

The del statement can delete individual elements or slices of elements.

It is often the simplest method to use.

A Practical Example

Given the following list:

year = [2010, 2011, 2012, 2013]

To delete the first two elements, you would type:

del year[0:2]

The left limit is included (0), while the right limit is excluded (2).

The final result is:

[2012, 2013]

And so on.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Lists

  1. What is a list
  2. Extracting elements from a list
  3. Removing an element
  4. Adding elements
  5. How to count occurrences in a list
  6. How to search for an element in a list
  7. Sorting a list
  8. Reversing the order of a list
  9. List comprehension
  10. Nesting list
  11. How to convert a tuple into a list