Whitehead
Whitehead

Reputation: 13

How can i store input in a list after a new line

I am new to python, I'm trying to take input of 2 numbers in a line T number of times, then store it in a list and calculate the sum of each two pairs of numbers in the list, but my list only stores the last two inputted numbers. It wont store anything before last new line. How can I store all the input ?

from operator import add
t = int(input())
i =  0
while i < t:
    n = input()
    L = list(map(int, n.split()))
    i += 1
sumL = (list(map(add, *[iter(L)]*2)))
print (sumL)

Upvotes: 1

Views: 1484

Answers (2)

Jonathan
Jonathan

Reputation: 5864

You are redefining the list in each loop interation.

You need to define list outside of the loop, and append inside of the loop.

Also, i'm not sure what you're trying to do.

code

t = int(raw_input("T: "))

x_sum = 0
y_sum = 0

for i in range(t):
    n = raw_input("%s: " % (i+1)).strip()
    x, y = n.split(' ')
    x_sum += int(x)
    y_sum += int(y)

print (x_sum, y_sum)

output

$ python test.ph
T: 2
1: 1 1
2: 2 2
(3, 3)

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

Initialize outside the loop and append L = list(map(int, n.split())) create a new list each iteration, you can also use range:

L = []
for _ in range(t):
    n = input()
    L.append(list(map(int, n.split())))

Or use a list comp:

L = [list(map(int, input().split())) for _ in range(t)]

You should be aware that will get an error if the user inputs anything that cannot be cast to an int, there is also no guarantee the user will enter data that can be split into two numbers so ideally you would use a try/except and validate the input.

You can also just list(map(sum,L):

L = [[1,2],[3,4]]

print(list(map(sum,L)))
[3, 7]

Upvotes: 4

Related Questions