Skip to content
Advertisement

How to take input in this form in python?

So, I want to take input of the following –

3
1 2
2 4
3 4

The first line contains an integer n. Each of the following n lines contains a pair of distinct space-separated integers. I want to store the inputs of first column in one array and the second column in another array. I came up with this code, can you tell me where I went wrong and how to do it?

n = int(input())
h = []
g = []
num = 0
for i in range(n):
    m = map(int,input().split("n"))
    h.append(m)
for j in range(n): 
    ni = map(int,input().split("n"))
    h.append(ni)

Advertisement

Answer

When you read using input you get the entire current line of input as a string, so each of your calls to input after the first will return '1 2', '2 4' and finally '3 4'.

You need to split those strings on (space) and then convert the values to integers and append them to the h and g lists. For example:

for i in range(n):
    this_h, this_g = map(int, input().split(' '))
    h.append(this_h)
    g.append(this_g)
print(h)
print(g)

Output:

[1, 2, 3]
[2, 4, 4]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement