3 ms·
>Wrap an iterable with enumerate and it will yield the item along with its index. Now that's a feature I wish I knew about sooner. I've been using: for it
by RyanMcGreal 16y ago
>Wrap an iterable with enumerate and it will yield the item along with its index.
Now that's a feature I wish I knew about sooner. I've been using:
for item in a:
print a.index(item), item
which has always felt kludgy.
- petdog 16y agoSeriously? You must enjoy your O(n^2).
- RyanMcGreal 16y agoThe sets I'm working on tend not to tend toward infinity.
- eru 16y agoYes. But the approach with index only works for actual sets. And if you have actual sets, you might as well use Python's built-in sets.
- eru 16y agoYes, enumerate is useful for that. But even if you did not now about it you could have used count from itertools to get the same effect: import itertools for (index, item) in zip(itertools.count(0), "hallo"): print index, item Itertools is worth checking out for other goodies, too.
- infinite8s 16y agoBefore enumerate, the standard idiom for this was: for i in range(len(a)): print i, a[i]