Issue
I have seen it both ways, but which way is more Pythonic?
a = [1, 2, 3]
# version 1
if not 4 in a:
print 'is the not more pythonic?'
# version 2
if 4 not in a:
print 'this haz more engrish'
Which way would be considered better Python?
Solution
The second option is more Pythonic for two reasons:
It is one operator, translating to one bytecode operand. The other line is really
not (4 in a)
; two operators.As it happens, Python optimizes the latter case and translates
not (x in y)
intox not in y
anyway, but that is an implementation detail of the CPython compiler.- It is close to how you'd use the same logic in the English language.
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.