Timeline for How to access the index value in a 'for' loop?
Current License: CC BY-SA 4.0
12 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Jun 10, 2023 at 21:55 | comment | added | vrnvorona | @saulspatz, repeating some code N times is not best with enumerate though. | |
Apr 22, 2021 at 10:04 | history | edited | mhhabib | CC BY-SA 4.0 |
python print version updated
|
Oct 6, 2020 at 18:27 | comment | added | ShadowRanger |
@Graham: Using range would be a premature pessimization, as zip (itertools.izip on Py2) is strictly better for that case. About the only use case for range I know of where there isn't a better alternative is iterating over overlapping slices of a sequence (where you need the index, but then use it to slice, so getting a value with the index isn't helpful). You could make it work without range (and for non-sequences) with itertools.tee , but it's ugly.
|
|
May 7, 2019 at 15:36 | comment | added | naoki fujita | This representation is useful when I use numba or cython. | |
Dec 29, 2018 at 16:17 | review | Suggested edits | |||
Dec 29, 2018 at 18:00 | |||||
Dec 23, 2018 at 16:33 | comment | added | Graham |
@chepner If one is iterating through multiple lists, using range may make sense. Though zip is probably more Pythonic for these cases, so using range would still be a premature optimization, as other comments mention.
|
|
Sep 15, 2017 at 23:15 | comment | added | chepner |
@adg I don't see how avoid enumerate saves any logic; you still have to select which object to index with i , no?
|
|
Mar 31, 2017 at 23:18 | comment | added | adg | Enumerate is not always better - it depends on the requirements of the application. In my current situation the relationships between the object lengths is meaningful to my application. Although I started out using enumerate, I switched to this approach to avoid having to write logic to select which object to enumerate. | |
Mar 15, 2017 at 6:31 | comment | added | januarvs | For Python 2.3 above, use enumerate built-in function since it is more Pythonic. | |
Aug 1, 2015 at 21:28 | comment | added | saulspatz | Use enumerate instead | |
Feb 6, 2009 at 22:52 | comment | added | Ben Blank |
That should probably be xrange for pre-3.0.
|
|
Feb 6, 2009 at 22:49 | history | answered | David Hanak | CC BY-SA 2.5 |