A string object is printed when input is taken for the list

Question:

l = list(input('enter a list:'))
print(l)

In this program ‘l’ is the variable which will take input from the user and return it as a list.

But when ‘l’ is printed it returns the integer as a string.

Output:

enter a list: 12345

['1', '2', '3', '4', '5']

Process finished with exit code 0

What is the problem with this code?

Asked By: ganesh murthy

||

Answers:

When you input 12345, you’re inputting a string – not an integer.

When you convert a string to a list the list will be comprised of the string’s constituent parts – i.e., all of its characters.

You’re asking the user to ‘enter a list’ and that’s exactly what’s happening – a list of characters

Answered By: DarkKnight

You can call int() to convert the characters to integers.

l = list(map(int, input("Enter a list:")))
print(l)

If you enter 12345 this will print [1, 2, 3, 4, 5]

Answered By: Barmar

All input is inputted as a string, and it’s up to you to cast/convert it to a different type if you need it. If you know the input is a string of digit, you can treat it as an iterable and explicitly convert every character to a digit:

mylist = [int(i) for i in input('Enter a series of digits: ')]
Answered By: Mureinik

If you want to create a list of integers from the user’s input, you can use a list comprehension or for loop to convert each character to an integer, something like this-

l = [int(i) for i in input('Give input:')]
print(l)

Why your solution is not working: In Python, the input function returns a string, which is a sequence of characters. When you pass the string to the list function, it creates a list of the individual characters in the string. For example, if you enter the string "12345", the list will be ['1', '2', '3', '4', '5'].

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.