Sorting of integers list in ascending order and adding all zeros at the end. Is there any best alternative than this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Sorting of integers list in ascending order and adding all zeros at the end. Is there any best alternative than this?

print("Hello world") list1=[4,0,3,6,1,0,2,0,1] l2=[] def func1(x): if x==0: l2.append(x) list1.sort(key=func1) print(l1) print(l2) list3=list1+l2 print(list3)

25th Jul 2020, 7:07 AM
Sevda Krithika Sharma
Sevda Krithika Sharma - avatar
8 Answers
+ 9
Sevda Krithika Sharma , the issue is the function you have defined. The requirements for a function used for key in sorting is: The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. the function returns some incorrect values = None May be you should think about an other approuch for your solution.
25th Jul 2020, 10:52 AM
Lothar
Lothar - avatar
+ 9
Sevda Krithika Sharma , i would recommend you to do it with a for loop. it's easy to understand. (1) you need 2 temp lists, one for all the zeros, the other for all numbers except zero (2) start the for loop by iterating the sorted list1 (3) check each element coming from list1 if it == 0 (4) append it in temp list for zeros (5) if element is non zero, append it to list for numbers (6) if iteration on list1 is done, your temp lists contains [0,0,0] and [1, 1, 2, 3, 4, 6] (7) last step print and concatenate the temp lists to final result later on you can use this basic version to rework it to a comprehenion. Happy coding!
25th Jul 2020, 11:15 AM
Lothar
Lothar - avatar
+ 8
a=[4,0,3,6,1,0,2,0,1] print([i for i in sorted(a) if i != 0] + [0]*a.count(0))
25th Jul 2020, 7:40 AM
Louis
Louis - avatar
25th Jul 2020, 7:10 AM
Baratov Hojiakbar
Baratov Hojiakbar - avatar
+ 4
list2.sort(key = lambda x: max(l) + 1 if x == 0 else x)
25th Jul 2020, 11:18 AM
Oma Falk
Oma Falk - avatar
+ 3
Sevda Krithika Sharma One liner 😃😃 print(sorted([x for x in list1 if x]) + [x for x in list1 if not x])
25th Jul 2020, 7:40 AM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
Thanks everyone for helping me out.
25th Jul 2020, 4:36 PM
Sevda Krithika Sharma
Sevda Krithika Sharma - avatar
0
xᴏᴊɪᴀᴋʙᴀʀ I have done in this way...I need other ways
25th Jul 2020, 7:26 AM
Sevda Krithika Sharma
Sevda Krithika Sharma - avatar