Remove item at index without pop in Python
Remove an item at a given index from a list without using pop by slicing the list around the index.
Python code
12 linesdef remove_at_index(lst, index):
"""Remove item at index and return the new list."""
if index < 0 or index >= len(lst):
raise IndexError("Index out of range")
return lst[:index] + lst[index + 1:]
if __name__ == "__main__":
items = [10, 20, 30, 40, 50]
result = remove_at_index(items, 2)
print(f"Original: {items}")
print(f"After removing index 2: {result}")
Output
Original: [10, 20, 30, 40, 50]
After removing index 2: [10, 20, 40, 50]
How it works
This function creates a new list by concatenating the slice before the index and the slice after the index. Slicing is a shallow copy, so integers and other immutable elements are preserved. The original list is not modified, which is useful when you need to keep the input unchanged. The index validation raises an IndexError to match Python's built-in behavior. This method is O(n) because slicing copies the remaining elements. It is a clean, readable pattern for functional-style list manipulation.
Common mistakes
- Forgetting to validate the index before slicing, which can silently produce wrong results.
- Modifying the original list in-place when the function is expected to return a new list.
- Confusing this with pop(), which removes and returns the element from the original list.
Variations
- Use del lst[index] to modify the list in-place without returning the removed element.
- Use list comprehension with enumerate to filter out the index.
Real-world use cases
- Removing an item from a list of config options while preserving the original list for rollback.
- Filtering out an outlier from a data array during preprocessing without altering the source.
- Building a new list of tasks when skipping one item in a UI queue based on its position.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.