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

boB Stepp robertvstepp at gmail.com
Sun May 30 21:31:01 EDT 2021


On Sun, May 30, 2021 at 7:40 PM dn via Tutor <tutor at python.org> wrote:
>
>
>
> On 31/05/2021 11.56, Manprit Singh wrote:
> > Dear sir ,
> > 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]
> >
> > 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]
> >>>>
> > Is this the correct way ? or is there something better that can be done ?
>
> +1 @Alan's comment.
> These appear highly academic questions with little apparent real-world
> application.

Or is Mr. Singh simply trying to understand the fine details of how
Python does things by coming up with these examples and exploring
them? I suspect that much exploration may have occurred (Which we
never get to see) before submitting his question with the intent of
getting validation of his conclusions. In any case, I found his
example quite stimulating.  I realized that I did not understand how
the "key" keyword parameter worked in sorted(),  when I did not see
how he got the result he had.  Of course I have not yet had any use
for that optional parameter.  I finally realized after playing around
in the interpreter and going to the docs multiple times that the key
function mapped each element in the original result to the following:
[2, 5, 0, 9, 0, 8] => [True, True, False, True, False, True], then
sorted this "Boolean" list where I had to keep in mind for sorting
purposes that False = 0 and True = 1.  Then sorted() apparently uses
this new order to reverse the mapping to get the end result of [0, 0,
2, 5, 9, 8].

So Mr. Singh's question caused me to learn multiple things tonight and
I am grateful to him!

Cheers!
boB Stepp


More information about the Tutor mailing list