4 ms·
Funny, I use them quite often. Enumerate will let you iterate anything iterable while also giving you your current index. for idx, item in enumerate(foo):
by whalesalad 5y ago
Funny, I use them quite often.
Enumerate will let you iterate anything iterable while also giving you your current index.
for idx, item in enumerate(foo):
if idx > 100:
break
otherwise()
I use the above example all the time to pluck the first few items from a generator when debugging, for instance. A generator is something that hasn’t been fully actualized, it might be an infinite list or streams for example.
Logging is also fun:
for idx, item in enumerate(thing):
logger.info(f’item {idx}: {item!r}’)
yield item
This could be used to wrap an existing iterator to just log each element with a counter prefixed. Also a handy debug tool.
range() is useful when you want an iterable of N size.
for i in range(num_tasks_to_create):
foo()
It can be used in this way to “do this thing N times”
Or you can use it other ways like:
if year in range(2000, 2020):
tl;dr I can think of a half dozen ways to use either!
- macintux 5y agoAha, thanks, I do occasionally need an index.
- memco 5y agoCheck out more-itertools which has things like take, tail and a bunch of other nice functions for working with iterators if you haven’t. Would allow you to do something like for el in take(100, iter): print(el) Plus there’s a bunch of other things in there for windowing, finding out whether or where empty stuff in the generator are. https://more-itertools.readthedocs.io/ https://more-itertools.readthedocs.io/
- whalesalad 5y agoI use this lib for this exact reason! Great suggestion. I wish the standard library had more functional functions like this. head/tail/take etc
- masklinn 5y agoIt… does? They’re called next, islice, and islice. more_itertools is nice but none of those 3 is a compelling argument for it.
- lou1306 5y agoBTW you can get head and tail with plain old unpacking :) >>> head, *tail = range(3) >>> head 0 >>> tail [1, 2] Granted, unpacking also coalesces lazy iterables (like range in this case) into lists, but if you aren't working with large/infinite iterables you should be alright.
- eesmith 5y agoAs a variant of your logging example, start enumerate at 1 to get the current line numbers: for line_num, line in enumerate(open("filename.txt"), 1): if not line.strip(): print(f"Empty line {line_num}.")