Skip to content Skip to sidebar Skip to footer

How To Convert N Space Separated Numbers Into In Array In Python?

How do I input n integers separated by space in python? Suppose I want to input n elements in an array separated by space such as 3 1 2 3 So is there any way to do it? EDIT - In f

Solution 1:

Two ways:

1) using raw_input(). This prompts user to enter inputs

int_list = [int(x) for x inraw_input("Enter integers:").split()]

2) using sys.argv, you can specify input from the command line

importsysint_list= [int(x) for x in sys.argv[1:]]

Solution 2:

numbers = input("Enter the numbers: ") #ask for input

numbersArray = [] #array to store the input

for number in numbers:
    numbersArray.append(number) #add input to the array

Not that at this point if for example the input is 1 2 3 then the array looks like this: ['1',' ','2',' ','3'] so you have to remove the ' ' from it:

numbersArray = numbersArray[::2]

Now testing with this input 1 2 3 calling print(numbersArray); will output ['1', '2', '3'] Hope this helps

PS. This is Python 3

Post a Comment for "How To Convert N Space Separated Numbers Into In Array In Python?"