Apparently
METHOD 1
if var in ['string one', 'string two']:
do_something()
is more Pythonic than:
METHOD 2
if var == 'stringone' or var == 'stringtwo':
dosomething()
Why is Method 1 considered more Pythonic than Method 2?
To be Pythonic is to use the Python constructs and datastructures with clean, readable idioms.
From: What is Pythonic?
Simply put, the first is easier to read than the second - it has less boilerplate, and less overhead than the first. Any Python programmer can look at the first and see that there's a list of things being checked against, and it reads much more like plain English than the second. Consider if you expanded the list of things being checked against - the first example would read like:
if var in ['string one', 'string two', 'string three']:
# If var is one of string one, string two, or string three.
do_something()
while the second would sound like:
if var == 'stringone' or var == 'stringtwo' or var == stringthree:
# If var is equal to stringone, or var is equal to stringtwo, or var is equal to stringthree.
dosomething()
It's easier to extend the first approach to more strings:
if var in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']:
The second approach quickly becomes unwieldy:
if var == 'one' or var == 'two' or var == 'three' or ...:
In addition, the first approach can be used to test a function call's return value, and only evaluates it once:
if bigCalculation() in ['one', 'two', 'three']:
The second approach must re-evaluate the call each time, leading to worse performance (especially if the call is computationally expensive).
if bigCalculation() == 'one' or bigCalculation() == 'two' or ...:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With