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?
A set is unique in Python. It does not allow duplicates.
Remove duplicates from list using Set. To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of set() method is that it returns distinct elements.
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)
into x not in y
anyway, but that is an implementation detail of the CPython compiler.
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