If I have a function:
if a_string == "a" or a_string == "b" or a_string == "c":
# do this
how can I write that differently without the repetitive or statements? Or is that the best way?
If I have a function:
if a_string == "a" or a_string == "b" or a_string == "c":
# do this
how can I write that differently without the repetitive or statements? Or is that the best way?
if a_string in ["a", "b", "c"]:
# do stuff
Make sure you use ==
in your conditions, not =
, or else Python will throw an error
EDIT: As Nigel Tufnel points out in his answer, you can also check for membership in a set
, e.g. {'a', 'b', 'c'}
. I believe this is actually faster in general, though it really won't matter practically if you only have three things in the list/set.
You can test for a list membership:
if a_string in ["a", "b", "c"]:
# do your thing
or you can test for a set membership:
if a_string in {"a", "b", "c"}:
# do your thing
or you can test for a tuple membership:
if a_string in ("a", "b", "c"):
# do your thing
I think that the list
way is the most pythonic way, the set
way is the most right way, the tuple
way is the most bizzare way.
EDIT: as DSM and iCodez have pointed out I was wrong: the tuple
way is the fastest (probably not, see EDIT#2) and the most pythonic way. Live and learn!
EDIT#2: I know that microbenchmarking is the most evil thing since Adolf Hitler but I'm posting it anyway:
python -O -m timeit '"c" in ("a", "b", "c")'
10000000 loops, best of 3: 0.0709 usec per loop
python -O -m timeit '"c" in ["a", "b", "c"]'
10000000 loops, best of 3: 0.0703 usec per loop
python -O -m timeit '"c" in {"a", "b", "c"}'
10000000 loops, best of 3: 0.184 usec per loop
I won't interpret the timeit
results but the set
timing is rather peculiar (probably it's because of the, er, I won't interpret the results).
if a_string in ("a", "b", "c"):
# do this
And you have an error in your example. Assignment "=" is not allowed in the "if" statement. You should use "==".
To add to the previous, in the specific case of checking for a single character in a string, you can do this:
if a_string in "abc":
Another similar idiom that you are likely to find useful is this:
Instead of:
if a_string == "abcdefg" or b_string == "abcdefg" or c_string == "abcdefg":
You can do this:
if any(i == "abcdefg" for i in (a_string, b_string, c_string)):