Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Print list after removing element at given index
Python lists are mutable data structures that allow you to store elements of different data types. Sometimes you need to remove elements at specific positions. This article demonstrates three methods to print a list after removing elements at given indices.
Using pop() Method
The pop() method removes and returns the element at the specified index. This is the most straightforward approach ?
# Original list
numbers = [10, 20, 30, 40, 50]
print("Original list:", numbers)
# Remove element at index 2
removed_element = numbers.pop(2)
print("Removed element:", removed_element)
print("List after removal:", numbers)
Original list: [10, 20, 30, 40, 50] Removed element: 30 List after removal: [10, 20, 40, 50]
Removing Multiple Elements
When removing multiple elements, remove from highest index first to avoid index shifting ?
# Remove elements at indices 0 and 2
data = [10, 20, 30, 'Hello', 67.9]
print("Original:", data)
# Remove index 2 first, then index 0
data.pop(2)
data.pop(0)
print("After removing indices 2 and 0:", data)
Original: [10, 20, 30, 'Hello', 67.9] After removing indices 2 and 0: [20, 'Hello', 67.9]
Using NumPy delete()
For larger datasets or when removing multiple indices, NumPy's delete() function is more efficient ?
import numpy as np
# Create list and convert to numpy array
data = [10, 20, 30, 'Hello', 67.9]
arr = np.array(data)
print("Original array:", arr)
# Remove elements at indices 0 and 2
new_arr = np.delete(arr, [0, 2])
print("After removal:", new_arr)
Original array: ['10' '20' '30' 'Hello' '67.9'] After removal: ['20' 'Hello' '67.9']
Using List Comprehension
Create a new list excluding elements at specified indices using list comprehension ?
# Original list
data = [10, 20, 30, 'Hello', 67.9]
indices_to_remove = [0, 2]
# Create new list excluding specified indices
new_list = [item for i, item in enumerate(data) if i not in indices_to_remove]
print("Original:", data)
print("After removal:", new_list)
Original: [10, 20, 30, 'Hello', 67.9] After removal: [20, 'Hello', 67.9]
Comparison
| Method | Modifies Original | Multiple Indices | Best For |
|---|---|---|---|
pop() |
Yes | Requires loop | Single element removal |
numpy.delete() |
No | Yes | Large datasets |
| List comprehension | No | Yes | Readable, Pythonic code |
Conclusion
Use pop() for simple single-element removal, NumPy delete() for large datasets, and list comprehension for readable code when removing multiple elements. Each method has its advantages depending on your specific use case.
