I have a list like below:
a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]
and I want to push all zeroes to the beginning of that list. The result must be like below.
a = [0, 0, 0, 0, 4, 5, 6, 7, 1, 5]
How to do it in Python 2?
In the beginning both target and source point to the last value of the array; if the *source is not 0, we replace *target with *source ; that is, if the last element is non-zero, we replace it by itself and decrease both target and source pointers; if the last element is 0, we don't copy it anywhere, only decrease the ...
While traversing, maintain count of non-zero elements in array. Let the count be 'count'. For every non-zero element arr[i], put the element at 'arr[count]' and increment 'count'. After complete traversal, all non-zero elements have already been shifted to front end and 'count' is set as index of first 0.
You could sort the list:
a.sort(key=lambda v: v != 0)
The key
function tells Python to sort values by wether or not they are 0
. False
is sorted before True
, and values are then sorted based on their original relative position.
For 0
, False
is returned, sorting all those values first. For the rest True
is returned, leaving sort to put them last but leave their relative positions untouched.
Demo:
>>> a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]
>>> a.sort(key=lambda v: v != 0)
>>> a
[0, 0, 0, 0, 4, 5, 6, 7, 1, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With