Issue 1749857: itertools.getitem() - Python tracker
Python Home About News Documentation Downloads Community Foundation Developer's Guide Issue Tracker Issues Search Random Issue Summaries Issues with patch Easy issues Stats User Administration User List Committer List Help Tracker Documentation Tracker Development Report Tracker Problem Issue1749857 ➜ This issue tracker has been migrated to GitHub , and is currently read-only . For more information, see the GitHub FAQs in the Python's Developer Guide.
Created on 2007-07-08 09:33 by doerwalter , last changed 2022-04-11 14:56 by admin . This issue is now closed . Files File name Uploaded Description Edit diff.txt doerwalter , 2007-07-08 09:33 Messages (2) msg52812 - (view) Author: Walter Dörwald (doerwalter) * Date: 2007-07-08 09:33 This patch adds itertools.getitem() which is basically equivalent to the following python code: _default = object() def getitem(iterable, index, default=_default): try: return list(iterable)[index] except IndexError: if default is _default: raise return default but without materializing the complete list.
Negative indexes are supported too. msg52813 - (view) Author: Raymond Hettinger (rhettinger) * Date: 2007-07-31 07:03 Rejected after an offline discussion with the OP. The use case for getitem(n) with n as a negative number depended on an unlikely combination of circumstances: * you have an iterable that is not a sequence (otherwise, just use s[-n]). * the iterable is somewhat large (otherwise, just list it into memory) * the iterable is finite (otherwise, getitem() dies in a infinite loop) * you only want one entry (otherwise, you'll have make multiple passes) * that entry is located near the end (otherwise getitem() is memory intensive) * you know the entry's offset from the end but not from the beginning * identifying the record of interest depends only on its position, not its content In the common case where the index is zero, the preferred spelling is to use the next() method -- that is its purpose.
For cases where the index is a positive integer, uing islice(it, n).next() suffices though it doesn't have the cute feature for a default value. History Date User Action Args 2022-04-11 14:56:25 admin set github: 45158 2007-07-08 09:33:32 doerwalter create Supported by The Python Software Foundation , Powered by Roundup Copyright © 1990-2022, Python Software Foundation Legal Statements