Search code examples
pythonstdinreadlinereadlines

How to read "n" lines at a time from stdin?


Consider the stdin has the following entries:

2  
a     
b     
3
d   
e   
f   

Now I would like to first read the number using n= sys.stdin.readline() and then read the next n lines using a function ReadNLines(n) into a list.

So the expected output is:

List1 = ['a','b']  
List2 = ['d','e','f']

Here is what I have tried. And I am looking for better timing performance.

import sys
def ReadNLines(n):
    List =[]
    for line in range(n):
        List.append(sys.stdin.readline())
    return List

if __name__ == "__main__":
    n = sys.stdin.readline()
    List1 = ReadNLines(n)
    n = sys.stdin.readline()
    List2 = ReadNLines(n)

Solution

  • You need to remove the newline that sys.stdin.readline() includes in the result. And you need to convert n to an integer.

    import sys
    def ReadNLines(n):
        List =[]
        for _ in range(n):
            List.append(sys.stdin.readline().strip())
    
    if __name__ == "__main__":
        n = int(sys.stdin.readline().strip())
        ReadNLines(n)
        n = int(sys.stdin.readline().strip())
        ReadNLines(n)
    

    Since you never use the line variable, the convention is to use _ as a dummy variable. You can also convert the function into a list comprehension:

    def readNLines(n):
        return [sys.stdin.readline().strip() for _ in range(n)]