When I tried to print all the elements in range(10), it lists 0 to 9.
But when I defined the end character to ‘,’ in “print", It shows only 2 to 9.
What’s the possible cause? Thanks!
>>> for i in range(10):
... print(i, end=",")
...
0,1,2,3,4,5,6,7,8,9,>>>
Does the end of the sequence appear if you add
print()
after the for loop? If so, it might well be that the output buffer needs to be flushed. I’m using a Mac. You appear to be using Windows, so it’s not entirely surprising that output buffering differs across platforms. I believe Python’s output is line buffered by default, which means the output buffer is flushed when the buffer fills up, or a newline character is emitted. Newline is the default end character, so explicitly setting it defeats the default flush behavior. On my machine my guess is the read-eval-print-loop (REPL) makes sure the last (partial) buffer has been flushed before the next prompt is displayed.
I’m actually more concerned that 0 and 1 don’t appear in your output.
Much appreciated for your answering! @smontanaro
Yes, I’m working on a Win10 system. The lists are fully presented if I added print() at the end of the loop, as you suggested.
However, it’s still hard for me to understand how the buffer works in Python at present.
I thought maybe the buffer size is limited to a certain number by default, but when I tried range(5), the elements 0 and 1 didn’t apear as well.
Really an interesting behavior for me. I may need more comprehension on this language.
I’d say “In addition to screenshots” here. I think the screenshot is valuable, so we know for sure what it looks like and that it didn’t get altered when copying it here.