[Tutor] to place all zeros of an existing list in the starting of a new list

Alan Gauld alan.gauld at yahoo.co.uk
Sun May 30 20:26:04 EDT 2021


On 31/05/2021 00:56, Manprit Singh wrote:

> Consider a list ls = [2, 5, 0, 9, 0, 8], now i have to generate a new list
> from this existing list , new list must contain all zeros in the starting,
> all other elements of the existing list must be placed after zeros in new
> list . So new list must be :
> new = [0, 0, 2, 5, 9, 8]

This is such a specific and unusual requirement that just about any way
of achieving it would be "correct". In particular, the zeros in the
original list and in the new list are all the same object since python
(or CPython) caches small integers, including zero.

In the more general case where we have a list of objects and you
want to create a new list putting some arbitrary group of objects
first followed by the rest, what happens then?

> The way I am doing it is :
>>>> ls = [2, 5, 0, 9, 0, 8]
>>>> sorted(ls, key=lambda x: x != 0)
> [0, 0, 2, 5, 9, 8]

This would seem to meet both the specific and general cases.
You only need to define the key function to identify the
retained cases.

Another, more generalized approach is to create two new lists,
one with the required elements, the other without, then add
these together. Like so:

>>> ls1 = [2,5,0,9,0,8]
>>> ls2 = [n for n in ls1 if n == 0]
>>> ls3 = [n for n in ls1 if n != 0]
>>> ls = ls2+ls3
>>> ls
[0, 0, 2, 5, 9, 8]

I suspect the sorted approach is quicker in this case.

But as you create more and more arcane requirements the
likelihood of there being a definitive or correct answer
or approach diminishes greatly.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list