Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take n numbers as input in single line in Python [duplicate]

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)

like image 533
Hash Avatar asked Dec 23 '22 09:12

Hash


2 Answers

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]
like image 98
rhoitjadhav Avatar answered Dec 28 '22 07:12

rhoitjadhav


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.

like image 37
Mritunjay Prasad Avatar answered Dec 28 '22 07:12

Mritunjay Prasad