it's my first question ever so I'll try to be as clear as I can. I noticed the next() functions and it seems a more elegant solution to use than the classical nested loop. So I run a simple code:
liste=['foo','bar','baz']
try:
G= (print(x) for x in liste)
print(next(G))
print(next(G))
print(next(G))
print(next(G))
except StopIteration:
print("That was obviously expected")
And I'm expecting:
foo
bar
baz
That was obviously expected
to appear on my screen, but instead I got:
foo
None
bar
None
baz
None
That was obviously expected
So my question(s) is simple:
Why are there None
responses after run ?
What is the good way and when is it the good moment to use next()
?
Thanks
Because print()
returns None
.
You are essentially doing print(print(..))
. The inner print
prints as you would expect ('foo'
, ...) but the outer prints the print which is where the None
comes from.