This is the inputlist input_list =[1,0,3,2,0,1,0] and I want output_list as [1,1,2,3,0,0,0] How to solve this?

Question:

input_list =[1,0,3,2,0,1,0]

for a in input_list:
    if input_list[a] != 0:
        input_list[a] = a 
    else:
        input_list[a] = 0
        
print(input_list)

Tried this but getting output as input_list =[1,0,3,2,0,1,0]
Instead i want this [1,1,2,3,0,0,0]

for a in input_list:
    if input_list[a] != 0:
        input_list[a] = a 
    else:
        input_list[a] = 0
        
print(input_list)
Asked By: T P

||

Answers:

You can make a custom sort where you give 0 infinite weight so it appears at the end of the sorting order.

output_list = sorted(input_list, key=lambda x: x if x != 0 else float('inf'))
Answered By: oskros

getting output as input_list

No, your code gives [0, 0, 3, 3, 0, 1, 0], because you use the values as indexes, for a in input_list iterates over values, then you use them input_list[a] as indexes


What you need is sorting, x or float('inf') expression takes inf in case the value of x is 0 (putting it at the end of the list), else it takes the value of x

input_list = [1, 0, 3, 2, 0, 1, 0]
result = sorted(input_list, key=lambda x: x or float('inf'))
print(result)
Answered By: azro
input_list =[1,0,3,2,0,1,0]
input_list.sort()
new_list = [el for el in input_list if el != 0] + [el for el in input_list if el == 0]

Output:

[1, 1, 2, 3, 0, 0, 0]
Answered By: imburningbabe

I think the cleanest way to solve this is:

import math
input_list =[1,0,3,2,0,1,0]

input_list = sorted(input_list, key=lambda x: x if x!=0 else math.inf)

Which is sorting like one would usually do, but giving the 0 a weight of inf (infinite) such that it’s always the last item.

Answered By: Mamiglia

There are already some good answers, here is just one more alternative approach, albeit more concise and little tricky:

Here it’s use the "True" and "False" of each number and its identity to move all "True" (number is zero) to the end of list.


L = [1,0,3,2,0,1,0]

ans = sorted(L, key=lambda x: (x ==0, x))

print(ans)
[1, 1, 2, 3, 0, 0, 0]

If you don’t want to create a new list, you can use the same list as this way:

L[:] = sorted(L, key=lambda x: (x ==0, x))
Answered By: Daniel Hao
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.