Home > Blockchain >  How to take inputs for an array using stdin function in same line in python?
How to take inputs for an array using stdin function in same line in python?

Time:02-05

This is my code:

N=int(stdin.readline())
Arr=[]
for j in range(N):
    Arr.append(int(stdin))
print(Arr)

I got the following error: TypeError: int() argument must be a string, a bytes-like object or a real number, not '_io.TextIOWrapper'

CodePudding user response:

To read one line from the console, use the input() function. After that use the split(" ") to split str to the string array by space delimiter.

line = input()
str_arr = line.split(" ")

To convert str array to int array. use the bellow code.

int_arr = [ int(item) for item in str_arr]

CodePudding user response:

There is a direct way to input list elements in python in a single line:

lst = [x for x in input().split()]          // for string input

and just use a int(x) inplace of x to convert into integers and store in list

CodePudding user response:

When you use readline you will get a string. To get an array you need to use the function split().

array = str.split()
  •  Tags:  
  • Related