I know that the and and or expressions exist in python, but is there any and/or expression? Or some way to combine them in order to produce the same effect as a and/or expression?
my code looks something like this:
if input=="a":
if "a" or "á" or "à" or "ã" or "â" in someList:
someList.remove("a") or someList.remove("á") or someList.remove("à") or someList.remove("ã") or someList.remove("â")
with this, I mean that if the user inputs “a” and any type of “a” is included in a previously defined list, can I have all the types of “a” removed from a given list?
python tells me that there is a problem in:
someList.remove("a") or someList.remove("á") or someList.remove("à") or someList.remove("ã") or someList.remove("â")
he tells me: ValueError: list.remove(x): x not in list
As Matt Ball‘s answer explains,
oris “and/or”. Butordoesn’t work withinthe way you use it above. You have to sayif "a" in someList or "á" in someList or.... Or better yet,That’s the answer to your question as asked.
Other Notes
However, there are a few more things to say about the example code you’ve posted. First, the chain of
someList.remove... or someList remove...statements here is unnecessary, and may result in unexpected behavior. It’s also hard to read! Better to break it into individual lines:Even that’s not enough, however. As you observed, if the item isn’t in the list, then an error is thrown. On top of that, using
removeis very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.Instead, I would suggest a very different approach. Filter the list using a
set, like so:Or, change the list in-place without creating a copy:
These both use list comprehension syntax to create a new list. They look at every character in
someList, check to see of the character is inchars_to_remove, and if it is not, they include the character in the new list.This is the most efficient version of this code. It has two speed advantages:
someListonce. Instead of performing 1000 tests, in the above scenario, it performs only 100.chars_to_removeis aset. If itchars_to_removewere alistortuple, then each test would really be 10 tests in the above scenario — because each character in the list would need to be checked individually.