0
0
PythonHow-ToBeginner · 3 min read

How to Remove Element from List in Python: Simple Methods

To remove an element from a list in Python, use list.remove(value) to delete by value, list.pop(index) to delete by position, or del list[index] to delete by index. Each method changes the list by removing the specified element.
📐

Syntax

Here are the common ways to remove elements from a list:

  • list.remove(value): Removes the first occurrence of value from the list.
  • list.pop(index): Removes and returns the element at index. If no index is given, removes the last element.
  • del list[index]: Deletes the element at index without returning it.
python
my_list.remove(value)
my_list.pop(index)
del my_list[index]
💻

Example

This example shows how to remove elements by value and by index using remove(), pop(), and del.

python
my_list = [10, 20, 30, 20, 40]

# Remove first occurrence of 20
my_list.remove(20)
print(my_list)  # Output: [10, 30, 20, 40]

# Remove element at index 2
removed = my_list.pop(2)
print(removed)  # Output: 20
print(my_list)  # Output: [10, 30, 40]

# Delete element at index 1
del my_list[1]
print(my_list)  # Output: [10, 40]
Output
[10, 30, 20, 40] 20 [10, 30, 40] [10, 40]
⚠️

Common Pitfalls

Common mistakes when removing elements from lists include:

  • Using remove() with a value not in the list causes a ValueError.
  • Using pop() or del with an invalid index causes an IndexError.
  • Expecting remove() to remove all occurrences instead of just the first.

Always check if the element or index exists before removing.

python
my_list = [1, 2, 3]

# Wrong: removing value not in list
# my_list.remove(4)  # Raises ValueError

# Correct: check before removing
if 4 in my_list:
    my_list.remove(4)

# Wrong: popping invalid index
# my_list.pop(5)  # Raises IndexError

# Correct: check index
if len(my_list) > 5:
    my_list.pop(5)
📊

Quick Reference

MethodDescriptionReturnsError if element not found
remove(value)Removes first matching valueNoneValueError if value not found
pop(index)Removes element at indexRemoved elementIndexError if index invalid
pop()Removes last elementRemoved elementIndexError if list empty
del list[index]Deletes element at indexNoneIndexError if index invalid

Key Takeaways

Use list.remove(value) to delete the first matching element by value.
Use list.pop(index) to remove and get an element by its position.
Use del list[index] to delete an element by index without returning it.
Check if the element or index exists to avoid errors when removing.
remove() only deletes the first occurrence, not all duplicates.