5
$\begingroup$

I know how to delete zeros from a simple list, but I have a list like the following:

list11 ={{2,4,0,0,0},{3,0,0,0,0},{9,4,3,0,0}}

How do I delete the zeros from this and create a list like the following:

{{2,4},{3},{9,4,3}}

Is this even possible since they have different lengths?

$\endgroup$
9
  • 2
    $\begingroup$ You can also do it like this: DeleteCases[{{2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}, {2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}, {2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}, {2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}, {2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}, {2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}, {2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}}, 0, {-1}] $\endgroup$
    – Moo
    Oct 5, 2016 at 1:13
  • 4
    $\begingroup$ DeleteCases[lst, 0, Infinity] also seems to work. $\endgroup$
    – Nasser
    Oct 5, 2016 at 1:51
  • 1
    $\begingroup$ DeleteCases[{9, 4, 0, 3, 0, 1}, 0, {-1}] $\endgroup$
    – Moo
    Oct 5, 2016 at 2:49
  • 10
    $\begingroup$ With v10.2 or later: {{2, 4, 0, 0, 0}, {3, 0, 0, 0, 0}, {9, 4, 3, 0, 0}} /. {0 -> Nothing} $\endgroup$
    – Bob Hanlon
    Oct 5, 2016 at 2:57
  • 1
    $\begingroup$ @BobHanlon And in earlier versions you can use Sequence[] instead of Nothing. $\endgroup$
    – wxffles
    Oct 5, 2016 at 3:17

2 Answers 2

7
$\begingroup$

According to the comments of Nasser

DeleteCases[list11, 0, Infinity]

{{2,4},{3},{9,4,3}}

$\endgroup$
3
$\begingroup$

Or instead of deleting the cases you don't want, you can select the cases you do want using UnequalTo:

Select[#, UnequalTo[0]] & /@ list11
{{2, 4}, {3}, {9, 4, 3}}
$\endgroup$
1
  • $\begingroup$ I've added a link in your answer because I didn't know and I found it very good $\endgroup$
    – LCarvalho
    Dec 4, 2016 at 19:13

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