How to append rows to different variables before appending to a list in python
Question: I have a input file like this

input:

    
    
    20
    
    23 121 20
    
    35 113 11
    
    12 15 142
    
    17 90 110
    
    58 12 198
    
    ......
    

I want to create to a list with numbers in each row assigned to a different
variable. I'm trying to do like this..

    
    
    def prog(inStr):
    
        input = inStr.split()
    
        N = int(input[0])
        list = []
    
        for i in range(N):
            row1 = int(input[1])
            row2 = int(input[2])
            row3 = int(input[3])
            r = prog(row1, row2, row3)
            list.append(r) 
    

But it's not working as it should, if executed like this..

    
    
    row1 = int(input[i*3+1])
    
    row2 = int(input[i*3+2])
    
    row3 = int(input[i*3+3])
    

Throws an error, index out of range.

Appreciate your help.


Answer: Rather than split your input on all whitespace, split it on _line separators_
first:

    
    
    def prog(inStr):
        lines = inStr.splitlines()
        N = int(lines[0])
        result = []
        for index in range(N):
            row1, row2, row3 = map(int, lines[index + 1].split())
    

If `inStr` came from a file or standard input, you could read from the input
directly:

    
    
    from itertools import islice
    
    test_count = int(next(fileobj))
    result = [r(*map(int, line.split())) for line in islice(fileobj, test_count)]
    

This uses a list comprehension,
[`itertools.islice()`](https://docs.python.org/3/library/itertools.html#itertools.islice)
to give a hard limit the number of iterations, and argument unpacking to
produce the result list.

