for i in range(100, -1, -1):
print(i)
for i in iter(range(100, -1, -1)):
print(i)
Which print's numbers from a list of 0 .. 100 numbers in descending order.
I know about sentinel attribute which stops once it reaches it, but besides that when should i consider using iter() function?
Thank you.
Not for this. iter() is good for turning things that would be memory-hungry iterables into generators, or for turning non-generator iterables that already exist into objects you can call next() on.
But range() is already a generator (well, not really, but it behaves very similarly to one and has the same advantages), so there's no benefit in this case.
For that matter, for for loops in general, if your iterable already fully exists, there's no point in making an iter() out of it - the for keyword does that behind-the-scenes already.
Here's an example. Say I have a list of items, where an item count is followed by that number of items, over and over.
[1, 'some data', 3, 'some data', 'some data', 'some data', 2, ...]
I might like to iterate over this data using nested for loops: the outer loop getting the item count, and the inner loop getting the following n elements of the list. The two loops can share an explicit iterator:
from itertools import islice
my_data = [1, "a", 3, "b", "c", "d", 2, "e", "f"]
my_iter = iter(my_data)
for i, count in enumerate(my_iter):
print(f"Round {i}")
for item in islice(my_iter, count):
print(f' {item}')
This code produces the output
Round 0
a
Round 1
b
c
d
Round 2
e
f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With