I want to be able to do something like this:
while next(gen):
print(value_from_gen)
I start with this list
x=[1,2,3,4,5]
Then I make a generateor to return the values
g = ({i:i*2} for i in x
)
When I try:
while val = next(g):
print(val)
I get:
File "main.py", line 6
while val = next(g):
^
SyntaxError: invalid syntax
When I try:
while next(g):
print(next())
It skips some values and I get the error:
{2: 4}
{4: 8}
Traceback (most recent call last):
File "main.py", line 7, in <module>
print(next(g))
StopIteration
when I try:
v= -1
while v is not None:
v=next(g)
print(v)
I get all the values but still get the error:
{1: 2}
{2: 4}
{3: 6}
{4: 8}
{5: 10}
Traceback (most recent call last):
File "main.py", line 8, in <module>
v=next(g)
StopIteration
When I try:
for v in g:
print(v)
I get the correct result:
{1: 2}
{2: 4}
{3: 6}
{4: 8}
{5: 10}
However, I am wondering if this is equivalent to calling next(g)
and does it keep the laziness benefit of the generator?
Also I am wondering if it is impossible to do this with an actual while loop?
Based on @Brad Martsberger's answer, you may pass False
to default parameter of next
function too:
while element:= next(g, False):
print(element)