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

dn PyTutor at DancesWithMice.info
Sun May 30 20:39:35 EDT 2021



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.

A learning opportunity for itertools?
"itertools — Functions creating iterators for efficient looping"
https://docs.python.org/3/library/itertools.html


import itertools as it

ls = [2, 5, 0, 9, 0, 8]

list( it.repeat( 0,
(len( ls ) - (
length_compressed := len( compressed := list( it.compress( ls, ls )
) ) ) ) ) ) + compressed

# [0, 0, 2, 5, 9, 8]


Is it "correct"?
- yes, in that it answers the question
- no, in that it is a ghastly mess to comprehend

Is it "better"?
- yes, I wrote it
- no, it is convoluted

However, it makes arcanely-amusing use of itertools!
-- 
Regards,
=dn


More information about the Tutor mailing list