1

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)
Dagrooms
  • 1,507
  • 2
  • 16
  • 42
Whitehead
  • 13
  • 4

2 Answers2

4

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]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

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)
Jonathan
  • 5,736
  • 2
  • 24
  • 22
  • 1
    The OP is using python3, they are also trying to sum each pair not get a total sum, you don't need strip, using `" "` is not needed and would actually cause an error if the user entered two spaces – Padraic Cunningham Jun 09 '15 at 21:50