AND/OR in Python?
As Matt Ball's answer explains, or
is "and/or". But or
doesn't work with in
the way you use it above. You have to say if "a" in someList or "á" in someList or...
. Or better yet,
if any(c in someList for c in ("a", "á", "à", "ã", "â")):
...
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:
someList.remove("a")
someList.remove("á")
...
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 remove
is 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:
chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]
Or, change the list in-place without creating a copy:
someList[:] = (c for c in someList if c not in chars_to_remove)
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 in chars_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:
- It only passes through
someList
once. Instead of performing 1000 tests, in the above scenario, it performs only 100. - It can test all characters with a single operation, because
chars_to_remove
is aset
. If itchars_to_remove
were alist
ortuple
, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.
x and y
returns true if both x
and y
are true
.x or y
returns if either one is true
.
From this we can conclude that or
contains and
within itself unless you mean xOR
(or except if and
is true)
or
is not exclusive (e.g. xor
) so or
is the same thing as and/or
.
Are you looking for...
a if b else c
Or perhaps you misunderstand Python's or
? True or True
is True
.