A command to return the maximum index of a list or array - the better len

Yes, for that reason, one might rightly hesitate to reuse it for another purpose, out of concern that it may cause confusion.

3 Likes

Aye. I revised my post and confessed my strong aversion to crossed meanings and their resultant ambiguity.

Pronouns drive me crazy, for example, because I can usually find three or four immediate candidates for this/that/him/her/it. Sometimes a dozen. At that point, comprehension of what is being communicated plummets.

Regarding the main object of the present discussion, it seems that the existing len built-in function is so closely related to the proposed new one, that implementing the proposed function as a built-in is not merited. The inconvenience that that proposed function mitigates is only a minor one. In my opinion, we should be rather conservative about creating new built-in functions, only doing so when it addresses a strong need.

With that having been said, what should the new built-in function return when it is applied to an empty list?

1 Like

Agreed. Unfortunately it comes up regularly, so the inconvenience sort of accumulates to a certain level.

ValueError or IndexError seem like the only rational options to me. What others might there be?

It does, in fact, sometimes bother me when situations arise wherein it is necessary to repeatedly subtract 1 from the length of a list, so I do understand @PLSeuJ’s concern. Perhaps in such situations, it is best to write a function to perform the calculation. While I don’t think a new built-in function should be created for this purpose, it is possible that the general community will see otherwise. If that is the case, and a new one is offered, we would need to carefully consider what reaction the function should have to an empty sequence.

Perhaps. Among the options of raising an exception or returning None or a negative number, it is unclear which would provide the most convenience, while also being least prone to leading to programming errors. But frequently having to handle the special case of an empty sequence might diminish some of the gain in convenience connected with not having to subtract 1 from its length. The fact that len always hands us back an int that truly represents the number of items in a sequence, even when it is empty, seems more elegant than needing to have a function handle that empty sequence as a special case.

1 Like

Excellent advice. A function can be protoyped and then tested for acceptance and utility in many ways. Maybe @PLSeuJ would consider making one.

Yes, the need to correctly interpret the returned value for an empty sequencer object is why I favored the exception. If you have to assert a non-empty sequencer object to debug and pre-empt the potential error, then the empty state is explicit. The assertion could now be considered a nuisance, though. It certainly adds more complexity to the code than a (-1) tucked into an expression.

1 Like