Python3 – list() is taking every character in the string as an element, not every word

Question:

I want to make a list of numbers via input
When I type:

>>> list(input())
1 23 456 7890
['1', ' ', '2', '3', ' ', '4', '5', '6', ' ', '7', '8', '9', '0']

how to let it print this:

[1, 23, 456, 7890]

?

Asked By: Nourddine1x1

||

Answers:

You can try:

>>> list(input().split(" "))
1 23 456 7890
['1', '23', '456', '7890']

If you want all elements as int in list, you can try:

>>> list(map(int, list(input().split(" "))))
1 2 34 567 890
[1, 2, 34, 567, 890]
Answered By: Harsha Biyani

You can try

[int(e) for e in input().split()]

This is a list comprehension that converts all split string in integers. It will raise an exception if string can not be converted to integers.

Answered By: Guillaume Jacquenot
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.