I am trying to read integers in a single line in a loop. For example if I need to read 5 nos I would need to read them from the runtime as suppose 1 3 2 1 2. The problem is I don't know beforehand how many integers I need to read as it will also be provided at the runtime.
So far I have tried this:
c1=input()
c1=int(c1)
for i in range(c1):
ar[i]=int(input())
but it reads integers as :
1
3
2
1
2
Can anyone help?
4 Answers 4
# if the enter is formatted as int plus white space. I think this would solve your problem.
num_str = input() # 1 3 2 1 2
num_str_arr = num_str.split(' ')
num_arr = [int(x) for x in num_str_arr]
print(num_arr)
# output: [1, 3, 2, 1, 2]
# with the list I believe you can do whatever you want.
Comments
Take the input using this command:
ar = input().split()
The input you will receive i.e ar[0] will be in class 'str'
In order to get integer you can use list comprehension
ar = [int(data) for data in input().split()]
Comments
Are you trying to do something like this?'
line = input()
ar = list()
for value in line.split():
ar.append(int(value))
print(ar)
Console
1 2 3 4 5
[1, 2, 3, 4, 5]
Comments
You could do it simply with a list comprehension which maps the strings to ints.
>>> [int(n) for n in input().split()]
2 3 4 5 6 7 8 9
[2, 3, 4, 5, 6, 7, 8, 9]
With this code you don't need to know how many there will be in advance. As they are all on the same line.
This has no error handling though for when you don't input valid integers (but the other answers don't either).
print(ar)what you want?