FAQ: Introduction to Lists in Python - Shrinking a List: Remove

Why isn’t it possible to use the remove() method using a negative index like garden_list.remove(-1) ?

To preserve code formatting in forum posts, see: [How to] Format code in posts

The remove method doesn’t take an index as it’s argument. Rather, your statement will remove the first occurrence of the element -1 from a list.

x = [3, "hello", 2, "bye", -1, True, -1, "xyz", 7]
x.remove(-1)
print(x) 
# [3, 'hello', 2, 'bye', True, -1, 'xyz', 7]

x.remove(18)  # ValueError (since 18 not in list)
""""""  

To remove an element from a specific index, you would use the pop method.

See brief descriptions of the available list methods in the Python documentation:
(5. Data Structures — Python 3.12.0 documentation)

Assuming you mean occurrences instead of indexes, the remove method by itself will only remove the first occurrence of the element. To remove all occurrences, there are a number of ways to accomplish the task. You could use the filter function or use a list comprehension or a loop or …

# Want to remove all occurrence of 4 from the list
nums = [1, 2, 4, 6, 4, 1, 3, 4, 11, 23]

# filter method
result = list(filter(lambda i: i != 4, nums))
print(result) # [1, 2, 6, 1, 3, 11, 23]

# List Comprehension
result = [n for n in nums if n != 4]
print(result) # [1, 2, 6, 1, 3, 11, 23]

# List Comprehension with Slice Assignment
nums[:] = [n for n in nums if n != 4]
print(nums) # [1, 2, 6, 1, 3, 11, 23]

# Loop (This will mutate the original list instead of creating a new list)
while 4 in nums: nums.remove(4)
print(nums) # [1, 2, 6, 1, 3, 11, 23]

# Loop (This will mutate the original list instead of creating a new list)
for i in range(nums.count(4)): nums.remove(4)
print(nums) # [1, 2, 6, 1, 3, 11, 23]
4 Likes

Thank you for the supreme reply. You answered my questions exactly! You are awesome! :smiley:

If you mean a specific method like remove_all(list, elem1, elem2) then nope, it does not exist. You can, however, perform such operation with a combination of multiple techniques. You already knew that remove method will remove the specific element from the list. There is also del whereby you can delete a specific element at corresponding index / position from the list.

If you want to perform the same operation multiple times, think off what mechanism or statements you can use / declare. If you want to only remove specific items that satisfy a given condition, think again on what structures or code syntaxes you can utilize with !

Was looking into the practice code for removing an item from a list and the printing the contents of the list.

For reference, this is the working code:

new_store_order_list = ["Orange", "Apple", "Mango", "Broccoli", "Mango"] new_store_order_list.remove("Mango") print(new_store_order_list)

This all makes sense, but I am wondering why I cant add the remove method in the print statement. For example, if I try to execute: print(new_store_order_list.remove(“Mango”)), it prints out “None”.

Just curious about why this is the case and what python is doing in the background when executing that print statement

.remove() like .sort() is an in place operation that has no return value, so gives nothing to print. We must perform the remove operation first, then print the list afterward.

2 Likes

Hello, perhaps this has been answered before I just haven’t been able to find an answer through here but…
is the .remove ( ) method only for letters and words or (strings)? and the del method for integers? and if so can the del method delete floats as well? thanks in advance!

.remove() Method

  • The .remove() method is used to remove the first occurrence of a specific value from a list. It works with any data type that is present in the list, including strings, integers, floats, and more.
my_list = [1, 2, 3, 4.5, 'hello']
my_list.remove(4.5)  # Removes the float 4.5 from the list
my_list.remove('hello')  # Removes the string 'hello' from the list
  • Limitation: It only removes the first occurrence of the value you specify. If the value is not found, it raises a ValueError.

del Statement

  • The del statement is used to delete objects, including entire lists, individual elements of lists, variables, or dictionary entries. It can delete items of any data type, including integers, floats, and strings.
my_list = [1, 2, 3, 4.5, 'hello']
del my_list[2]  # Removes the element at index 2 (which is the integer 3)
del my_list  # Deletes the entire list
  • Flexibility: del can be used to delete variables and entire data structures, not just individual elements.
3 Likes

Glad you differentiated between method and statement. We need to keep track of what is in the built-in core library and what is in the core class definitions.

Keep at it.


Aside

I would add that del doesn’t care what object it deletes. It deletes an object, simple as that. Done and dusted; object gone.

We can delete a list; why? Because it is an object. We can delete an element of a list; why? Because it is an object. If it’s not an object, del can’t deal with it.

del self
Traceback (most recent call last):

  Cell In[15], line 1
    del self

NameError: name 'self' is not defined
2 Likes

Just to elaborate on the info you’ve already gotten.

You can find bits about .remove here: https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types and here https://docs.python.org/3/tutorial/datastructures.html#more-on-lists.

All it does is finds the first element where == evaluates to True and removes it so it’s the same method for int, str or otherwise. It’s simply a matter of whether the value passed == an element of the list.

A bit more info-

It’s so close to equality testing that a few dirty edge cases occur like-

x = [True]
x.remove(1.0)
print(x)  # Output: []
# because True == 1.0 in Python

but that’s just one of the few ugly implicit conversions left behind in Python (the same sneaky behaviour affects dict types too which also work on equality tests, see https://docs.python.org/3/library/functions.html#hash).

You can do a similar silly thing by making an object that always equates to True.

The main point here is it removes by equality testing elements.


As for del, most folks won’t need to use this statement. My two cents would be to not worry about it for the time being. Wait until it’s actually taught or find a high quality resource to explain it e.g. https://realpython.com/python-del-statement/ (note this has to introduce details about Python’s memory model and namespace handling, del is not a beginner friendly statement). It was probably a mistake for me to try and explain something by using it.

If you're very curious about del-

You can read about it here: https://docs.python.org/3/reference/simple_stmts.html#the-del-statement. I would note however that del doesn’t delete an object per se. It just removes the reference to it.

x = myobject
y = [x]
del y[0]
print(x)  # x is still bound to the object

Note del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero.

What this technical quote from the documentation means is that del itself does not destroy objects.

To fully understand del though you’d need to understand how Python handle objects in the first place which probably won’t be introduced for a while. A good thing to look up in the future but probably not useful at this point in the course.

5 Likes

Hey, what to do if I want to remove all the duplicates of “Mango” at ones? Is here some option like this? :thinking: Thank you :slight_smile:

The simplest way to remove duplicates is to build a new list from the old one, while testing against the new list as we iterate over the old one.

old_list = ["Orange", "Apple", "Mango", "Broccoli", "Mango"]
new_list = []
for x in old_list:
    if x in new_list:
        continue
    new_list.append(x)

print (new_list)
# ['Orange', 'Apple', 'Mango', 'Broccoli']

While it may be possible to mutate the list in situ (the way `list.sort() does) the logic is tricky and probably not a good idea to include in this post.

Now to answer your other question,

Look for the post close to to top of this thread in which @tgrtim explains it very well. Namely, that the list.remove() method only removes the first item it encounters and is not greedy (as in removing all).

2 Likes