-1

I'm trying to sort a list with space like,

my_list = [20 10 50 400 100 500]

but I got an error

"ValueError: invalid literal for int() with base 10: '10 20 50 100 500 400 '"

code:

strength = int(input())
strength_s = strength.sort()
print(strength_s)
pault
  • 41,343
  • 15
  • 107
  • 149
  • try changing your first line to `strength = map(int, input().split())` – pault Apr 22 '19 at 15:50
  • 2
    Possible duplicate of [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user) – pault Apr 22 '19 at 15:51

3 Answers3

1

The input function in python returns the entire line as a str.
So, if you enter a space separated list of ints, the input function will return the entire line as a string.

>>> a = input()
1 2 3 4 5

>>> type(a)
<class 'str'>

>>> a
'1 2 3 4 5'

If you want to save this as a list of integers, you have to follow the following procedure.

>>> a = input()
1 2 3 4 5
>>> a
'1 2 3 4 5'

Now, we need to separate the numbers in the string, i.e. split the string.

>>> a = a.strip().split()  # .strip() will simply get rid of trailing whitespaces
>>> a
['1', '2', '3', '4', '5']

We now have a list of strings, we have to convert it to a list of ints. We have to call int() for each element of the list, and the best way to do this is using the map function.

>>> a = map(int, a)
>>> a
<map object at 0x0081B510>
>>> a = list(a)  # map() returns a map object which is a generator, it has to be converted to a list
>>> a
[1, 2, 3, 4, 5]

We finally have a list of ints

This entire process is mostly done in one line of python code:

>>> a = list(map(int, input().strip().split()))
1 2 3 4 5 6
>>> a
[1, 2, 3, 4, 5, 6]
Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36
0

Get inputs with space from the user:

strength = list(map(int, input().strip().split()))

Sort them:

strength.sort()

And print:

print(strength)
Sabareesh
  • 711
  • 1
  • 7
  • 14
0

To begin with, my_list = [20 10 50 400 100 500] is neither a list, nor the correct way to represent one. You represent a list using my_list = [20, 10 ,50, 400, 100, 500] .
I will assume my_list is a string. So then you will split the string into a list, convert the list to an integer and then sort it, like so

my_list = "20 10 50 400 100 500"
li = [int(item) for item in my_list.split(' ')]
print(sorted(li))
#[10, 20, 50, 100, 400, 500]

To make your original code work, we would do

strength = input()
strength_li = [int(item) for item in strength.split(' ')]
print(sorted(strength_li))

And the output will look like.

10 20 40 30 60
#[10, 20, 30, 40, 60]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40