64

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.

MisterMiyagi
  • 36,972
  • 7
  • 82
  • 99
Underyx
  • 1,519
  • 1
  • 17
  • 23

12 Answers12

106

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]
>>> 
Amit Joki
  • 56,285
  • 7
  • 72
  • 91
greentec
  • 1,860
  • 1
  • 17
  • 15
  • http://introtopython.org/lists_tuples.html#List-Comprehensions maybe this is helpful. – greentec Feb 28 '17 at 05:31
  • Can this accept different data types other than int? i.e. Can I replace `int(x)` with `string(x)` – Stevoisiak Nov 02 '17 at 15:10
  • @StevenVascellaro Yes although the expression would be str(x) instead of string(x) since str is python's way of saying string – Vikhyat Agarwal Jan 08 '18 at 12:40
  • 6
    @DhirajBarnwal If you want to know what's going on there: `input()` to read input + `split()` to split the input on spaces + `[f(x) for x in iter]` to loop over each of those + `int` to turn each into an int. If you want to know how one can come up with it: it's mostly just figuring out what you want to do and which pieces you need to put together to achieve that. – Bernhard Barker Feb 20 '18 at 21:14
  • I would have +1 if you had an extra 2 lines of explanation which @Dukeling did in the comments. – Rishav Mar 13 '19 at 04:16
59

It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:

Python 3:

s = input()
numbers = list(map(int, s.split()))

Python 2:

s = raw_input()
numbers = map(int, s.split())
Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
  • 2
    After python 2.7 raw_input() was renamed to input(). Stack overflow [answer](http://stackoverflow.com/a/954840/318807) – AJ Dhaliwal Apr 15 '16 at 11:29
  • what if my input is having mixed datatype string and integer then how can i split them and convert to list. input: 'aaa' 3 45 554 'bbb' 34 'ccc' i added the contents seperated by space!! – frp farhan May 06 '17 at 16:25
  • @FarhanPatel That's an unrelated question, so I suggest asking a new question. Start with looping over `s.split()` or `shlex.split(s)` if you want to allow spaces inside quoted strings. – Sven Marnach May 06 '17 at 16:30
  • posting it as a new question, thnx for the encouragement, was scary it might not be marked as duplicate!! http://stackoverflow.com/questions/43822895/how-to-separate-a-mixed-datatype-string-taken-as-input-into-list – frp farhan May 06 '17 at 16:42
7

eval(a_string) evaluates a string as Python code. Obviously this is not particularly safe. You can get safer (more restricted) evaluation by using the literal_eval function from the ast module.

raw_input() is called that in Python 2.x because it gets raw, not "interpreted" input. input() interprets the input, i.e. is equivalent to eval(raw_input()).

In Python 3.x, input() does what raw_input() used to do, and you must evaluate the contents manually if that's what you want (i.e. eval(input())).

Karl Knechtel
  • 56,349
  • 8
  • 83
  • 124
6

You can use .split()

numbers = raw_input().split(",")
print len(numbers)

This will still give you strings, but it will be a list of strings.

If you need to map them to a type, use list comprehension:

numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)

If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval

Sean Vieira
  • 148,604
  • 32
  • 306
  • 290
5

Another way could be to use the for-loop for this one. Let's say you want user to input 10 numbers into a list named "memo"

memo=[] 
for i in range (10):
    x=int(input("enter no. \n")) 
    memo.insert(i,x)
    i+=1
print(memo) 
Ayan Khan
  • 51
  • 1
  • 5
4
num = int(input('Size of elements : '))
arr = list()

for i in range(num) :
  ele  = int(input())
  arr.append(ele)

print(arr)
rashedcs
  • 3,209
  • 2
  • 35
  • 39
1

you can pass a string representation of the list to json:

import json

str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)

user enters in the list as you would in python: [2, 34, 5.6, 90]

Anthon
  • 59,987
  • 25
  • 170
  • 228
Logan
  • 11
  • 3
1

Answer is trivial. try this.

x=input()

Suppose that [1,3,5,'aA','8as'] are given as the inputs

print len(x)

this gives an answer of 5

print x[3]

this gives 'aA'

Hadi
  • 4,840
  • 10
  • 44
  • 66
1
a=[]
b=int(input())
for i in range(b):
    c=int(input())
    a.append(c)

The above code snippets is easy method to get values from the user.

1

Get a list of number as input from the user.

This can be done by using list in python.

L=list(map(int,input(),split()))

Here L indicates list, map is used to map input with the position, int specifies the datatype of the user input which is in integer datatype, and split() is used to split the number based on space.

.

enter image description here

Integraty_beast
  • 430
  • 3
  • 18
1

I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.

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

Here is my ouput:

11111
[1, 1, 1, 1, 1]
Asim Khan
  • 23
  • 3
  • What if I want to pass `1, 11, 111`or maybe `11, 1, 111`? In your program they will all just be `1, 1, 1, 1, 1, 1`... Bottom line, this only works for ***single digit*** numbers which is pretty restrictive... – Tomerikoo Apr 08 '21 at 14:09
0

try this one ,

n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
    a=raw_input()
    if(a.isdigit()):
        l1.insert(i,float(a)) #statement1
    else:
        l1.insert(i,a)        #statement2

If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.

Tunaki
  • 125,519
  • 44
  • 317
  • 399
xarvier
  • 1
  • 1