Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is one approach more Pythonic than the other? [closed]

Tags:

python

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?

like image 812
Rahul Sharma Avatar asked Dec 01 '22 21:12

Rahul Sharma


2 Answers

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()
like image 133
Peter Sobot Avatar answered Dec 24 '22 01:12

Peter Sobot


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 ...:
like image 35
BrenBarn Avatar answered Dec 24 '22 00:12

BrenBarn