Elements missing when printing a range with self-defined end character

I’m learning python, this might be a silly question. Anyway, please refer to the screenshot below:


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!

Hmmm… It works for me:

>>> 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.

1 Like

What happens with range(10, 20)?

The missing 0,1, has been overwritten by the >>> prompt.
Add print() at the end to avoid this.

3 Likes

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. :grinning_face:

Oh, you’re right!

It has nothing to do with buffering.
The prompt starts with a \r I expect on Windows.
See what this does.

print(‘abcdefghi\rxyx`)
1 Like
>>> print('abcdefghi\rxyx')
xyxdefghi

@barry-scott Thanks Scott!

Instead of screenshots, do what the respondents did and copy and paste input/output text between

```

lines. Note: I used alternate ~~~ lines to get the triple backline line above. This allows us to copy and paste posted code bits or whatever.

1 Like

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.

3 Likes

Thanks! @tjreedy
Just noticed the topic " About the Python Help category"