On Apr 10, 2020, at 12:46, Chamoun Saoma <[email protected]> wrote:
>
> I have an idea to improve the python language through the creation of a new
> and very readable function.
> #################
> def ranlen(x):
> #range of length of x
> return range(len(x))
> #################
I find this less readable. The abbreviation “ran” frequently means “random”;
occasionally it means other things; I can’t think of any place where it means
“range”.
Also, not every one-liner needs to be a builtin. Look at the docs to see how
short the list is. That’s important—not for performance or for making it easier
to write alternative implementations (although it does help both of those a
bit), but because there’s so little to learn and keep in your head as a novice,
or as an occasional user who comes back to Python every few weeks while mostly
working in Kotlin, or whatever. The things that are there are all hard to get
right, or easy to get wrong, or need access to internals, or can benefit from a
custom C-optimized implementation in CPython, etc. There’s no builtins for
identity (a function that returns its argument), dummy (a function that takes
any args and ignores them and does nothing), inc (a function that adds 1),
etc., because when you do happen to need them, you (even a novice or an
occasional Python user) can write them yourself without even slowing down.
Finally, far from being essential to many algorithms, this is actually an
antipattern, or at least a code smell—most code that’s doing it should be doing
something else:
for x in xs:
dostuff(x)
xs = [x+1 for x in xs]
xs[:] = [x+1 for x in xs]
for i, x in enumerate(xs):
xs[i] = x+i
for x, y in zip(xs, ys):
print(x + y)
… and so on. The alternatives are almost always clearer, more declarative,
harder to get wrong, more general (e.g., working with all iterables rather than
just sequences), and more efficient than what you would have written with a
loop over the range.
So, what about, say, the case where you explicitly want to loop over the first
len(xs) of ys, and it should be an exception if ys is too short rather than
stopping early so you can’t use zip? Sure. You could actually use zip_longest
with a sentinel fillvalue, or other stuff from itertools—but sometimes maybe a
loop over the range does make more sense. (There’s a reason those functions are
in itertools rather than builtins.) But those are unusual cases. Which means
they usually deserve to be called out. A change that makes it look less visible
and less unusual would actually be counterproductive.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/CWVIUNDBNPMZT3LR4PTJ23DL4CYSCQ7E/
Code of Conduct: http://python.org/psf/codeofconduct/