Remove an Element by Index in Python

In Python, we can remove an element at a specific index in a list. Python provides several methods to remove an element by index, such as del, pop(), and slicing. In this tutorial, we will explore different ways to remove an element from a list using an index.


Examples

1. Using the del Statement

The del statement allows us to delete an element at a specific index from a list.

</>
Copy
# Creating a list
fruits = ["apple", "banana", "cherry", "orange"]

# Removing the element at index 2
del fruits[2]

# Printing the updated list
print("Updated List:", fruits)

In this example, we:

  1. Defined a list named fruits containing four elements.
  2. Used the del statement with fruits[2] to remove the element at index 2 (third element, “cherry”).
  3. Printed the updated list after deletion.

Output:

Updated List: ['apple', 'banana', 'orange']

2. Using the pop() Method

The pop() method removes an element at a specific index and also returns the removed element.

</>
Copy
# Creating a list
colors = ["red", "blue", "green", "yellow"]

# Removing the element at index 1
removed_color = colors.pop(1)

# Printing the updated list and removed element
print("Updated List:", colors)
print("Removed Element:", removed_color)

In this example:

  1. We created a list named colors with four elements.
  2. Used colors.pop(1) to remove and store the element at index 1 (“blue”) in the variable removed_color.
  3. Printed the updated list and the removed element.

Output:

Updated List: ['red', 'green', 'yellow']
Removed Element: blue

3. Using List Slicing

List slicing allows us to create a new list by excluding the element at the specified index.

</>
Copy
# Creating a list
numbers = [10, 20, 30, 40, 50]

# Removing element at index 3 using slicing
numbers = numbers[:3] + numbers[4:]

# Printing the updated list
print("Updated List:", numbers)

In this program, we:

  1. Defined a list named numbers with five elements.
  2. Used slicing numbers[:3] + numbers[4:] to exclude the element at index 3 (“40”) and create a new list.
  3. Printed the updated list.

Output:

Updated List: [10, 20, 30, 50]

Conclusion

Python provides multiple ways to remove an element by index:

  1. del: Deletes an element without returning it.
  2. pop(): Removes and returns the element at the specified index.
  3. List Slicing: Creates a new list excluding the unwanted element.

The choice of method depends on whether you need to store the removed element (pop()) or just delete it directly (del). Slicing is useful when working with immutable data structures.