valueerror: list.remove(x): x not in list – Code Example

Total
0
Shares

Python throws valueerror: list.remove(x): x not in list when an item is not present in the list and still you are trying to remove it. Let’s understand this with an example –

Alice: Bob! Please remove eggs from the basket.
Bob removed eggs from basket
Alice: Bob! I said remove eggs from basket.
Bob: How can I remove again. It’s not in the basket. I have already removed it.

From the above conversation between Bob and Alice, we can deduce two things –

  1. Eggs were there in the basket but Bob removed it and can’t remove again.
  2. Eggs were not in the basket and Alice was insisting to remove it.

Similarly, Python throws valueerror: list.remove(x): x not in list when either x is not in the list or already removed and we try to remove again.

Common point of mistake

Why would anybody try to remove a value again if they know they have already removed it? Well, it happens due to inline editing in lists.

Suppose you are looping over a list and removing items from it then there is a good chance of error. Because the length of list will change and loop will work unpredictably.

Always create a copy of the list (if it is small) and run loop over it. Or, carefully manage the values.

Solution with Code Example

Error Code – Let’s first reproduce the error –

lst = ['Ironman', 'Hulk', 'Thor', 'Hawkeye']
lst.remove('Captain')

Since Captain is not in the list so it will throw the error –

Traceback (most recent call last):
  File "/home/jdoodle.py", line 2, in <module>
    lst.remove('Captain')
ValueError: list.remove(x): x not in list

2. Error due to multiple loops –

lst = ['Ironman', 'Hulk', 'Thor', 'Hawkeye']

for i in lst:
    for j in [1,2]:
        lst.remove(i)

Due to inner loop, the remove function will run twice on the same value of i.

Correct Code

1. Check if the value exists

lst = ['Ironman', 'Hulk', 'Thor', 'Hawkeye']

for i in lst[:]:
    for j in [1,2]:
        if i in lst:
            print(i, "removed")
            lst.remove(i)
        else:
            print(i, "not in list")

Pay attention that we are not running loop on lst. We create a copy of list and run loop over it.

Output –

Ironman removed
Ironman not in list
Hulk removed
Hulk not in list
Thor removed
Thor not in list
Hawkeye removed
Hawkeye not in list

2. Use try-except block

lst = ['Ironman', 'Hulk', 'Thor', 'Hawkeye']

for i in lst[:]:
    for j in [1,2]:
        try:
            lst.remove(i)
            print(i, "removed")
        except:
            print(i, "not in list")

Output –

Ironman removed
Ironman not in list
Hulk removed
Hulk not in list
Thor removed
Thor not in list
Hawkeye removed
Hawkeye not in list

Live Demo

Open Live Demo