Hamsa
Hamsa

Reputation: 483

How to read integers in a single line into an array in a loop in python?

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?

Upvotes: 0

Views: 632

Answers (4)

Paul Rooney
Paul Rooney

Reputation: 21619

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).

Upvotes: 0

PaxPrz
PaxPrz

Reputation: 1928

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()]

Upvotes: 1

Andrew.K.S
Andrew.K.S

Reputation: 56

# 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.

Upvotes: 1

user3657941
user3657941

Reputation:

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]

Upvotes: 0

Related Questions