-4
code:
list=['1','85863','432','93','549834']
list.sort()
print (list)

Actual output:
>>> 
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']

I have tried other sort operations also but they are displaying same output. when i tried to read list from keyboard input they are reading only strings but not int please help me why?

Pavan Nath
  • 1,494
  • 1
  • 14
  • 23

5 Answers5

2

when i tried to read list from keyboard input they are reading only strings but not int please help me why

if x is a string, just use int(x) to convert to int

You're sorting strings (text), not by numerical values like integers

For your expected output you have to convert to ints first

my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]

Now you can sort numerically, and get a list of ints

my_list.sort()

N.B. avoid using list as variable name, it is a Python built-in

bakkal
  • 54,350
  • 12
  • 131
  • 107
2

I presume you want to sort by the sum to match your expected output:

l = ['1','85863','432','93','549834']

l.sort(key=lambda x: sum(map(int,x)))

print(l)
['1', '432', '93', '83863', '549834']
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

You need to first convert the strings to int.

list = [int(ele) for ele in list]
list.sort()
print list
Aiken
  • 88
  • 5
0

Without int:

lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)

This give:

['1', '93', '432', '85863', '549834']

And if you want integers…

my_int = int(input())
Clodion
  • 1,017
  • 6
  • 12
0

I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

Pavan Nath
  • 1,494
  • 1
  • 14
  • 23