2

I am looking for a single line command in python to convert an integer input to list. The following is the situation.

mylist=[]
mylist=list(input('Enter the numbers: '))

The above line works perfectly if i give more than one number as input. Eg 1,2,3 . But it gives Error when i give only a single digit entry. Eg: 1 . Saying it cannot convert an integer to list. I don't want to run a loop asking user for each input. So i want a one line command which will work for one or more digits input given by user separated by commas.

Thanking you, -indiajoe

3 Answers 3

3

I think that the simplest thing that you can do is:

mylist = map(int, raw_input('Enter the numbers: ').split(','))

But it's nearly the same that using a list comprehension.

Sign up to request clarification or add additional context in comments.

Comments

3

You should use raw_input and convert to int with a list comprehension:

user_input = raw_input('Enter the numbers: ')
my_list = [int(i) for i in user_input.split(',')]

From the offical documentation: raw_input reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

5 Comments

You can also use eval to convert your string list to int: mylist = map(eval, mylist)
Thanks, but i was trying to precisely avoid this loop. Isn't there any one liner for this common use? If not, I shall go ahead with this loop method.
@SRC: It's a bad practice to use eval on a user input! You should do that only if really needed and with the necessary check.
@indiajoe: You will have the loop anyway, could be hidden inside map but there will be anyway! Given so, to choose between a list comprehension or map (or filter etc...) is mearly a matter of taste. Nevertheless you should be aware that in python-3 map is a generator expression so in case one day you'll find yourself porting your own code just remember to wrap map with list (if you need a list and not a generator), like list(map(...)).
@RikPoggi: Thanks for the info regd the python 3.
1

input eval()'s what you type. So, when you type 1,2,3, the result is a tuple; when you type 1, the result is an int. Try typing 1, instead of 1. Note that your first line (mylist=[]) is unnecessary.

2 Comments

Yes, typing a comma after integer works. Eg: 1, But looks a little untidy to ask a user to put extra comma. Or I will have to add a try: except: block to catch it and correct.
Following this approach, this will work: mylist=list(eval(raw_input('Enter the numbers: ')+',')). (Doing the eval with raw_input and the comma).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.