Although that is not a pattern I recall I had needed, but for the first item in a generator, I recognize it is more complicated than it should to be able to do that.
However, not only that would be too big a change for all this objects I think one would expect an object providing index access with `[]` to also have a `len`. Also, see it as potentially making a lot of code error-prone: let's say one gets passed a generator where a sequence is expected. In current Python, if an item is accessed by index, one just get an explicit IndexError. If objects change to having indexes, two consecutive access to `gen[1]` will consume the generator and return different values. That could be very confusing. On the other hand, as I said, I can't come up with a simple pattern to get the nth item - so probably we should think of an easy and performant way. One way I can think of is to have a named parameter to the `next` built-in that would allow one to move forward more than one position. Say: `fith_element = next(gen, skip=4) ` and finally, one way I could think of retrieving the n element is: In [19]: a = (i for i in range(0, 100, 10)) In [20]: next(b for i, b in enumerate(a) if i==5) Out[20]: 50 It definitely feels like there should be a simpler way, but I just could not come up with it. On Tue, 17 Nov 2020 at 10:35, Nuri Jung <[email protected]> wrote: > How about enabling subscription operator (`[]`) for generator expressions? > Also for all `zip()`, `key()`, etc. They could be evaluated in the > background only for the requested amount, to avoid evaluating the whole > expression to something like a list or tuple, then indexed. > _______________________________________________ > 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/WDJWOB4NVIIQPJWBNZCF5K4SXZJIARFZ/ > Code of Conduct: http://python.org/psf/codeofconduct/ >
_______________________________________________ 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/BB4ZMINMSVUG4N5XOB7P25FZW2IRV67K/ Code of Conduct: http://python.org/psf/codeofconduct/
