Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

26
  • 1579
    Playing devil's advocate. I don't understand why this idiom is considered pythonic. 'Explicit is better then implicit', correct? This check doesn't seem very explicit about what is is checking. Commented Nov 22, 2011 at 6:14
  • 290
    @JamesMcMahon - it's a trade-off between explicitness and type flexibility. generally, "being explicit" means not doing "magical" things. on the other hand, "duck typing" means working with more general interfaces, rather than explicitly checking for types. so something like if a == [] is forcing a particular type (() == [] is False). here, general consensus seems to be that duck typing wins out (in effect, saying that __nonzero__ is the interface for testing emptiness docs.python.org/reference/datamodel.html#object.__nonzero__) Commented May 31, 2012 at 14:50
  • 137
    This method doesn't work on numpy arrays.. so I think if len(a) == 0 is preferable both in terms of "duck typing" and implicitness. Commented Mar 20, 2019 at 18:01
  • 14
    @sleblanc I've never seen a null terminated array in c outside of implementing a string, the common case is not to null terminate. "comparing its length to zero is utterly inefficient" is incorrect, there is no c implementation in existence where this would cost more than a couple cycles. Comparing the length of an array to 0 to determine emptiness is standard practice in c and almost all c influenced languages (c++, java, c#, etc). Commented Apr 14, 2019 at 4:52
  • 124
    Coming from a language that claims to be some sort of poetry, this mechanism is pure garbage. Semantically, being empty is very different to not being Commented Apr 4, 2020 at 14:03