3
$\begingroup$

If I have a list of lists with different lengths:

{{1, 2, 3}, {1}, {1, 2, 3, 4}, {x}, {1, x}, {2}, {2, 3}}

How can I extract all the sub-lists with no symbols:

{{1, 2, 3}, {1}, {1, 2, 3, 4}, {2}, {2, 3}}

There must be an easy way to do this but I can't find it. Unfortunately, I'm not so good with Mathematica to be able to modify similar cases that I found(for example Link1 and Link2) to the problem at hand.

$\endgroup$

3 Answers 3

6
$\begingroup$
Cases[{{1, 2, 3}, {1}, {1, 2, 3, 4}, {x}, {1, x}, {2}, {2, 3}}, {__?NumericQ}]
$\endgroup$
3
  • 4
    $\begingroup$ Or 3 underscores if empty lists should also be kept. $\endgroup$ Commented Mar 17, 2016 at 21:42
  • $\begingroup$ Perfect! Thank you. $\endgroup$
    – MathX
    Commented Mar 17, 2016 at 21:44
  • $\begingroup$ Or DeleteCases[ {{1, 2, 3}, {1}, {1, 2, 3, 4}, {x}, {1, x}, {2}, {2, 3}}, {___, _Symbol, ___}] $\endgroup$
    – xyz
    Commented Mar 18, 2016 at 1:58
5
$\begingroup$

Another approach is to use VectorQ:

lis = {{1, 2, 3}, {1}, {1, 2, 3, 4}, {x}, {1, x}, {2}, {2, 3}};
Select[lis, VectorQ[#, NumericQ] &]

(* {{1, 2, 3}, {1}, {1, 2, 3, 4}, {2}, {2, 3}} *)

Variations:

Select[lis, AllTrue[#, NumericQ] &]
$\endgroup$
4
$\begingroup$

I think @march's answer is probably the best way. Here's another for giggles...

Select[{{1, 2, 3}, {1}, {1, 2, 3, 4}, {x}, {1, x}, {2}, {2, 3}}, ! MemberQ[#, _Symbol] &]
$\endgroup$
2
  • $\begingroup$ Interesting. What is the name of that _Symbol part? I want to search for other properties that have the same usage. $\endgroup$
    – MathX
    Commented Mar 17, 2016 at 23:24
  • 2
    $\begingroup$ @BehzadNazari That's shortcut for Blank[Symbol] which is a pattern match for a certain Head. Head[x] (if x isn't defined) evaluates to Symbol. Try Head /@ {x, 1.0, 1, "test"} for examples. $\endgroup$
    – kale
    Commented Mar 18, 2016 at 2:10

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.