'How to convert N space separated numbers into in array in Python? [closed]
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
In the first line we are given n and in the next line n inputs follow. How can I store them in an array?
Solution 1:[1]
Two ways:
using
input()1 and. This prompts the user to enter inputs:int_list = [int(x) for x in input("Enter integers:").split()].split()separates the values in the input by spaces.using
sys.argv, you can specify input from the command lineimport sys int_list = [int(x) for x in sys.argv[1:]]
1raw_input() in Python 2
Solution 2:[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'].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mkrieger1 |
| Solution 2 | mkrieger1 |
