3 ms·
Nothing to important but, just for readers who may be unfamiliar with Python, your last example can be rewritten in a quite idiomatic Pythonic way: for i i
by p4bl0 3y ago
Nothing to important but, just for readers who may be unfamiliar with Python, your last example can be rewritten in a quite idiomatic Pythonic way:
for i in range(len(iterable)):
...
- lou1306 3y agoOr, in case you need both `i` and `iterable[i]` within your loop: for i, item in enumerate(iterable): ...
- Mikhail_Edoshin 3y agoYes, all this works. These are Pythonic ways. But see, here the `enumerate` function will allocate a new number and a tuple for the number and the item. Then `i, item` will unpack that tuple and deallocate the tuple memory. All this happens quickly (in a loop it may be essentially the same memory for every tuple) and CPython is well optimized for that, of course, but it is not free. With an integer cursor (`i`) there are no unique numbers for each item and no temporary tuples. This is slightly cheaper. And also more flexible, which is the main point I'm trying to make. Other loop constructs are meant to be used in certain way and will not work otherwise. Integer cursors are not meant to be used in any special way, you can combine them as you wish. They give the maximum possible flexibility from the beginning. You can loop in any direction, by multiple items or by a variable number of items, over many iterables at once, changing the iterables as you go, and so on. (A special case in Python are list comprehensions; these are useful because most of that “comprehending” happens inside CPython and thus they are faster.)