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?
Use input(), map() and split() function to take space-separated integer input in Python 3. You have to use list() to convert the map to a list.
Thanks. Easy solution is just to use the string method split. input: 5 8 0 sgshsu 123 input. split(" ") == ["5", "8", "0", "sgshsu", "123"] #Then they are easy to convert to numeric datatypes, but invalid inputs might raise errors.
To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.
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 line
import sys
int_list = [int(x) for x in sys.argv[1:]]
1raw_input()
in Python 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With