Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more 'pythonic' for 'not' [duplicate]

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?

like image 349
ThePrimeagen Avatar asked Jul 15 '13 16:07

ThePrimeagen


People also ask

Which Python data type does not allow duplicates?

A set is unique in Python. It does not allow duplicates.

How will you remove a duplicate element from a list?

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.


1 Answers

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.

  • It is close to how you'd use the same logic in the English language.
like image 70
Martijn Pieters Avatar answered Oct 10 '22 03:10

Martijn Pieters