Explain Codes LogoExplain Codes Logo

How to remove an element from a list by index

python
list-manipulation
python-functions
data-structures
Anton ShumikhinbyAnton Shumikhin·Sep 10, 2024
TLDR

To remove an item quickly from a list by index, you can use pop(index):

my_list.pop(2) # Adieu, third item, you "popped" out!

Remember, pop() modifies the list in-place and returns the removed element. It's like a magic trick making the item disappear and reappear, but if you don't specify the index, the trick is played on the last item:

my_list.pop() # Au revoir, last item!

Breaking down the solution

Scratching off an item with del

If you don't need to meet the element again (not even for a farewell coffee!), del is your weapon:

del my_list[1] # Second item, you're out! But no hard 'del'ings!

Want to say goodbye to a whole slice? No problem:

del my_list[2:5] # Item 2 to 4, you've been 'del'eted!

Psst! After you del or pop(), the remaining elements slide to the left. You're shifting indices, not just making items invisible!

Using pop() for later reunions

Once upon a time, you eliminated an item but needed to use it later. pop() heard you:

removed_element = my_list.pop(3) # Third item, dare to 'pop' out?

Because pop() doesn't sing the "scan me whole" chorus like list.remove(value), it's faster at index sent-offs.

Hand-picking elements with list comprehension

Got a finicky eater who doesn't like the veggies? Filter them out:

indexes_to_ignore = {2, 3, 5} my_list = [item for i, item in enumerate(my_list) if i not in indexes_to_ignore] # We're playing favorites!

Advanced takeaways

Order of Operations with Multiple Indices: del

Always del from right to left, else you'll get an IndexError surprise:

# Right way, All-right! del my_list[5] del my_list[2] # Wrong way, All-wrong! del my_list[2] del my_list[5]

Watch Out for Pitfalls - Reference Gotchas with Slicing

Slicing creates a new list. Looks innocent but when your code gets romantic, things get complicated:

another_list = my_list my_list = my_list[:2] + my_list[3:] # another_list scoffs at your amorous moves!

Choose your Fighter: Efficiency Showdown

del is leaner and strongest. It cuts right to the chase. No fanfare, no bells.

However, pop() can be the people's champion if you want to show off the vanquished. Plus, unlike del, it keeps the relatives (references) of your list informed.