How is one approach more pythonic than the other?

Apparently

METHOD 1

if var in ['string one', 'string two']: do_something() 

more Pythonic than:

METHOD 2

 if var == 'stringone' or var == 'stringtwo': dosomething() 

Why is method 1 considered more Pythonic than method 2?

+4
source share
2 answers

To be Pythonic, you need to use Python constructs and data structures with clean, readable idioms.

From: What is Pythonic?

Simply put, the first is easier to read than the second - it has fewer templates and less overhead than the first. Any Python programmer can look at the first and see that there is a list of things to check, and he reads much more than ordinary English than the second. Think if you have expanded the list of objects to be scanned - the first example will look like this:

 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 will sound like this:

 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() 
+13
source

It’s easier to extend the first approach to more lines:

 if var in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']: 

The second approach is quickly becoming cumbersome:

 if var == 'one' or var == 'two' or var == 'three' or ...: 

In addition, the first approach can be used to check the return value of a function call and evaluates it only once:

 if bigCalculation() in ['one', 'two', 'three']: 

The second approach is to reevaluate the call every time, which leads to worse performance (especially if the call is expensive).

 if bigCalculation() == 'one' or bigCalculation() == 'two' or ...: 
+5
source

Source: https://habr.com/ru/post/1438324/


All Articles