[0, 0, 0, 1, 1, 1, 0] ... remove all 0 values

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Jul 8 10:57:16 EDT 2009


Daniel Austria a écrit :
> Hi python - hackers,
> 
> just one question. How can i remove all 0 values in a list? Sure - i
> can loop over it, but that s not a neat style.  list.remove() will
> only remove the first occurence. Doing that while no exception is
> raised is also uncool, right?
> 
> Some suggestions?

the_list = [0, 0, 0, 1, 1, 1, 0]

# Simple solution
print [x for x in the_list if x != 0]

# if you want to mutate the list 'in place':
the_list[:] = [x for x in the_list if x != 0]
print the_list

HTH



More information about the Python-list mailing list