ValueError: x is not in list
ValueError: x is not in list in Python means list.index() and list.remove() raise when the item is missing. Check with `in` first, or catch ValueError.
How do I fix ValueError: x is not in list?
ValueError: x is not in list comes from list.index() or list.remove() when the item is missing. Unlike str.find(), they raise instead of returning -1. Test first with if item in my_list:, or wrap the call in try/except ValueError. If the item looks present, compare types and spelling.
- 1. Guard with inWrite if tag in tags: tags.remove(tag), or queue.index(name) if name in queue else -1.
- 2. Compare with repr()Print repr(item) and repr(the_list). A stray space or different case means the values are not equal.
- 3. String versus number"3" is not 3. Convert with int() or str() so the item matches the type stored in the list.
What does ValueError: x is not in list mean?
Unlike str.find(), which returns -1, list.index(x) raises ValueError when x is absent, and list.remove(x) does the same. Python 3.14 words it "list.index(x): x not in list"; older versions quote the value, as in "'zoe' is not in list".
Why does ValueError: x is not in list happen?
1. Looking up something that may be absent
index() assumes the item is there.
Breaks
position = queue.index(name)Works
position = queue.index(name) if name in queue else -12. Removing an item that was already removed
remove() raises on the second call.
Breaks
tags.remove(tag)Works
if tag in tags:
tags.remove(tag)3. A near miss: case, spaces or type
"Zoe" is not "zoe", and "3" is not 3.
Breaks
ids.index("3") # ids holds intsWorks
ids.index(int("3"))How to find it in your own code
Print the item and the list. If the item is genuinely absent, handle that case explicitly. If it looks present, compare repr() of both: a stray space, different case, or a string versus an int is the usual cause.
Try it: fix this bug
easysafe_find_index([1, 2], 99) raises ValueError: 99 is not in list.
def safe_find_index(items, target):
return items.index(target)More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.