Search code examples
pythonstringstdin

What does "for x in sys.stdin" do exactly?


Simple question here, but I can't find a definitive answer. I'm writing some python code and I'm confused as to what this line does exactly:

a = []
for x in sys.stdin:
    c = x.split()
    a.extend(c)

When I run it, it defaults to making a list of words, but why is that? Why does python default to words instead of lines, or even characters from the stdin? I know about the readlines and readline methods, but I'm confused as to what exactly this code is doing with the stdin.


Solution

  • File objects, including sys.stdin, are iterable. Looping over a file object yields lines, so the text from that file up to the next line separator.

    It never produces words. Your code produces words because you explicitly split each line:

    c = x.split()
    

    str.split() without arguments splits on arbitrary-length whitespace sequences (removing any whitespace from the start and end), effectively giving you a list of words, which are then added to the a list with list.extend().