5
$\begingroup$

I have a list of lists which looks something like this- {{12,1,23,.....,4},{0,0,0,.....,0},{34,67,5,.....,60},{0,0,0,.....,0}}. I want list to look something like - {{12,1,23,....,4},{34,67,5,.....,60}}. I want to remove all those lists which have zero as their only element. How can It be done?

$\endgroup$
1

3 Answers 3

11
$\begingroup$
list = {{12, 1, 23, 4}, {0, 0, 0, 0}, {34, 67, 5, 60}, {0, 0, 0, 0}};

DeleteCases[ list , {0 ..}]
(* {{12, 1, 23, 4}, {34, 67, 5, 60}} *)

(* this also results in the same answer *)
Cases[ list , Except@{0 ..}]

(* or *)
list /. {0 ..} :> Sequence[]

(* using select *)
Select[ list , x \[Function] FreeQ[x, {0 ..}] ]

(* assuming no negative integers *)
Select[ list , Total @ # != 0 &]
$\endgroup$
3
  • 2
    $\begingroup$ caution: the last method with Select assumes that there are no negative integers ! $\endgroup$
    – Ali Hashmi
    Commented Apr 15, 2017 at 14:42
  • $\begingroup$ I thought my edit helps readability. Please, roll back, if you think it does not. (+1) for a nice answer! $\endgroup$
    – gwr
    Commented Apr 15, 2017 at 15:55
  • $\begingroup$ @gwr thanks for the edit. it is definitely better now $\endgroup$
    – Ali Hashmi
    Commented Apr 15, 2017 at 15:55
6
$\begingroup$

Another possibility as of Version 11:

lists = {{12, 1, 23, 4}, {0, 0, 0, 0}, {34, 67, 5, 60}, {0, 0, 0, 0}};

lists /. {0..} -> Nothing
$\endgroup$
0
4
$\begingroup$

A slight addition:

Pick[dat, Total /@ Unitize@dat, Except[0 | _List]]

Just providing some other methods of solving similar problems.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.