On Tue, Aug 24, 2021 at 7:23 PM MRAB <pyt...@mrabarnett.plus.com> wrote:
> On 2021-08-25 00:48, Guido van Rossum wrote: > > Hi Tim, > > > > I'm sorry if this has been brought up before, but *aside from PEP 8* is > > there anything wrong with using "if len(a)" for nonempty, or "if not > > len(a)" for empty? > > > What is the cost of 'len'? If it's always O(1), then it's not a problem, > but if it's not O(1) (counting the items in a tree, for example) and > you're not interested in how many items there are but only whether > there's at least one, then... > It's a pretty universal assumption that len() is O(1) -- something that doesn't do that probably shouldn't implement __len__(). (And yeah, there's probably some tree package around that does implement an O(N) __len__(). People do a lot of silly things though, we can't handle *everything*.) > It would seem to work for numpy and pandas arrays, and it works for > > builtin sequences. Also, it has the advantage of being 100% backwards > > compatible. :-) > > > > Surely conforming to PEP 8 shouldn't need an addition to the language or > > stdlib? Or does it not work? > It was pointed out to me that numpy allows arrays that have no elements but a nonzero first dimension. People could disagree about whether that should be considered empty. I'm not sure about Pandas, but IIRC a Dataframe is always a table of rows, with all rows having the same number of columns. Here I'd say that if there's at least one row in the table, I'd call it non-empty, even if the rows have no columns. This conforms to the emptiness of [()]. It's possible that there's a common use case in the data science world where this should be counted as empty, but to me, that would be inconsistent -- a row with zero columns is still a row. (For numpy arrays my intuition is less clear, since there's more symmetry between the dimensions.) So then the next question is, what's the use case? What code are people writing that may receive either a stdlib container or a numpy array, and which needs to do something special if there are no elements? Maybe computing the average? AFAICT Tim Hoffman (the OP) never said. PS. Why is anyone thinking that an array containing all zeros (and at least one zero) might be considered empty? That seems a totally different kind of test. -- --Guido van Rossum (python.org/~guido) *Pronouns: he/him **(why is my pronoun here?)* <http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-change-the-world/>
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/3FKVLFJLVZIARGNIA7VQBJS3V3BAD3O5/ Code of Conduct: http://python.org/psf/codeofconduct/