Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of numbers as input from the user

Tags:

python

list

input

I tried to use input (Py3) /raw_input() (Py2) to get a list of numbers, however with the code

numbers = input() print(len(numbers)) 

the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.

like image 587
Underyx Avatar asked Jan 11 '11 22:01

Underyx


People also ask

How do you take a list of inputs in one line in Python?

To take list input in Python in a single line use input() function and split() function. Where input() function accepts a string, integer, and character input from a user and split() function to split an input string by space.

How do you take n number inputs in Python?

Use map() function and split() function to take n number of inputs in Python. input(): takes user input. split(): splits the string into sequence of elements means converts whitespace into commas (,), split function applicable only for string data type.


1 Answers

In Python 3.x, use this.

a = [int(x) for x in input().split()] 

Example

>>> a = [int(x) for x in input().split()] 3 4 5 >>> a [3, 4, 5] >>>  
like image 157
greentec Avatar answered Sep 28 '22 08:09

greentec