How To Take N Numbers As Input In Single Line In Python
Solution 1:
The following snippet will map the single line input separated by white space into list of integers
lst = list(map(int, input().split()))
print(lst)
Output:
$ python test.py
1 2 3 4 5
[1, 2, 3, 4, 5]
Solution 2:
This will convert numbers separated by spaces to be stored in ar:
ar = list(map(int, input().strip().split(' ')))
Strip() is used to remove all the leading and trailing spaces from a string, so that it is clear and easy to classify/distinguish inputs.
Solution 3:
There are various methods to do this. User can enter multiple inputs in single line separated by a white space. Let's say I want user to enter 5 numbers as
1 2 3 4 5
This will be entered in a single line. But keep in mind that any input is considered a string in python. So you'll have to convert these values into integer values. Also, you would need to access these entered values separately. For that, you can convert the values to integer and add them into list. In python, strangely enough, there are no arrays, but lists. So your code should look something like this:
mylist=list(map(int,input("Enter 5 numbers: ").split())
You might want to look at implementation of split()
and map()
functions. You can find them in the official documentation. But here is a little explanation:
The map(func,seq)
function will convert the input one by one to the function supplied, int in this case. This function is equivalent to a for loop which iterates over the elements one by one and applies some transformation function. The split()
function will split the input by white spaces if no separator is supplied in the brackets. By default, map() function returns a map object. So to convert it into a list, we use list()
.
Hope this clarifies your doubt.
Solution 4:
To input an array of known length:
n = int(input()) # for size
Array = list(map(int, input().split(' ')[:n])) # to input n elementsprint(Array)
Solution 5:
To enter the numbers in one line and in limits
limit = int(input("Enter your limit : "))
arr = list(map(int,input(""Enter your number : ").split()[:limit]))
Post a Comment for "How To Take N Numbers As Input In Single Line In Python"