On Fri, Dec 27, 2019 at 02:22:48AM -0000, Marco Sulla via Python-ideas wrote: > It's very common to see: > > ``` > for i, x in enumerate(sequence): > [...] > > ```
Yes, that is very common, except that "sequence" can be any iterable with an unpredictable length, or even an infinite length, such as a generator: def gen(): while some_condition: yield some_value and enumerate will still work. > and also to see > > ``` > for i in range(len(sequence)): > [...] > > ``` That, on the other hand, should not be common. > I propose to introduce for sequences the methods `indexes()` and `entries()`. Hmm, well, that will cause a lot of code duplication. Just in the built-ins, we would have to add those two methods to: - dicts - dict views (keys, values and items) - sets - frozensets - lists - tuples - strings - bytes - bytearrays (did I miss any?). Even if the methods can share an implementation (probably calling enumerate and range behind the scenes) that's still over twenty additional methods to be added, documented, tested and maintained. What benefit does this change give us? for i, x in enumerate(items): # works with every iterable for i, x in items.entries(): # only works with some sequences So we save one character when typing. We don't simplify the language, we make it more complicated: def function(iterable): if hasattr(iterable, "entries"): entries = iterable.entries() else: entries = enumerate(iterable) for i, x in entries: ... So to save one character, we add four lines. Yeah, nobody is going to do that. They'll just use the technique that works on all iterables, not the one that works on only some of them. for i in range(len(sequence)): for i in sequence.indexes(): Here we save two characters and one function call. The cost is, every sequence type has to implement the method. I don't see enough benefit to force every sequence to implement two new methods. -- Steven _______________________________________________ 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/NHDAGETBAKLZT4BDLNSNXM6ETSCBPQKJ/ Code of Conduct: http://python.org/psf/codeofconduct/