How to take n numbers as input in single line in Python

32,620

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 elements
print(Array)
Share:
32,620
Hash
Author by

Hash

Updated on July 21, 2022

Comments

  • Hash
    Hash almost 2 years

    Like in C++ how can I ask user input upto a range

    Below is the code to take user input in c++

    #include<iostream>
    using namespace std;
    int main() {
        int array[50];
        cin>>n;
        //ask a list
        for(i = 0; i<n; i++){
            cin>>array[i];
        }
    }
    

    How can I ask user input like above in Python 3? (I don't want to take the inputs in different lines)

  • Hash
    Hash about 6 years
    but can it be done within for loop? The variable should take input even the user press enter or in the same line like in c,c++
  • David Buck
    David Buck almost 4 years
    How will this work? Other answers use variants of input().split() which outputs a list of strings that can be converted to int with map. In your answer, the output from input() will be a single string, so it's essentially the same as list1=int(input())