Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move all zeroes to the beginning of a list in Python

Tags:

python

list

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?

like image 585
namco Avatar asked May 24 '14 12:05

namco


People also ask

How do you move all zeroes to front of an array?

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 ...

How do you move zeros to the end of a list?

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.


1 Answers

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]
like image 117
Martijn Pieters Avatar answered Oct 12 '22 23:10

Martijn Pieters