I am taking a datacamp tutorial and am wondering if someone could please explain why this code prints out the ODD numbers up to 11? I was thinking each next() call steps through the sequence, but if I follow this thought, the first print should be the number 2 (count(0) goes to count(1) when it first hits the while and then when it prints, it should go to count(2).
TIA.
from itertools import count
sequence = count(start=0, step=1)
while(next(sequence) <= 10):
print(next(sequence))
1 3 5 7 9 11
next(sequence)
, as the name says, will get the next element in the provided sequence.
Once an element is obtained, a further call to next(sequence)
will simply yield the next number after that one (providing we are reusing the same sequence
).
>>> sequence = count(start=0, step=1)
>>> next(sequence)
0
>>> next(sequence)
1
>>> next(sequence)
2
Note that, if you re-generate the sequence, you'll start over:
>>> sequence = count(start=0, step=1)
>>> next(sequence)
0
>>> next(sequence)
1
>>> sequence = count(start=0, step=1)
>>> next(sequence)
0
In your code you are calling next(sequence)
on the while condition, and then next(sequence)
for the print
function, so both values will be different. Basically, as the next
calls are alternated between the while
and the print
you'll see that the print
will print out the odd values.
You can see a similar behavior if you add one more next
:
from itertools import count
sequence = count(start=0, step=1)
while(next(sequence) <= 10):
noop = next(sequence)
print(next(sequence))
This will print out 2 5 8 11
If you'd want to print out the even numbers instead, you can:
Start counting from 1
:
from itertools import count
sequence = count(start=1, step=1)
while(next(sequence) <= 10):
print(next(sequence))
This will print out 2 4 6 8 10
Or, if you'd like 0
to be there too, just add a single print
statement before the while
loop:
from itertools import count
sequence = count(start=0, step=1)
print(next(sequence))
while(next(sequence) <= 10):
print(next(sequence))
This will print out 0 2 4 6 8 10
If you'd want to print each of the numbers, simply persist the output of next(sequence)
:
from itertools import count
sequence = count(start=0, step=1)
element = next(sequence)
while(element <= 10):
print(element)
element = next(sequence)
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