3
$\begingroup$

I'd like to check if all elements of a list are numbers. I've tried

t = {5/4, 12}
MatrixQ[t, NumberQ]
MemberQ[t, NumberQ]
And @@ Table[NumberQ[t[[i]]], {i, 1, Length[t]}]

but only the last one yields the desired result. Is there a better way to check?

$\endgroup$
  • 3
    $\begingroup$ VectorQ[t, NumberQ] or AllTrue[t, NumberQ] should do the trick - the VectorQ version only accepts lists of numbers, while the AllTrue version accepts any head $\endgroup$ – Lukas Lang Jul 22 at 8:02
  • $\begingroup$ Maybe ContainsOnly[t[[All, 0]], {Rational, Integer}] possibly with the addition of Real and/or Complex $\endgroup$ – Coolwater Jul 22 at 8:15
  • $\begingroup$ @LukasLang, Thanks, I like your answer the best. Sorry I cannot upvote it! $\endgroup$ – Patricio Jul 22 at 8:22
  • $\begingroup$ Table[ Im[z] == 0, {z, t} ] $\endgroup$ – LouisB Jul 22 at 8:23
  • 2
    $\begingroup$ I'm confused both by the question asking for Reals and NumberQ as if they were the same when they are not, and by the fact that Irrationals like $\pi$ and $e$ are not NumberQ. You are getting contradictory answers! Can you please edit and clarify? $\endgroup$ – rhermans Jul 22 at 8:34
3
$\begingroup$

Given a list:

list = {Pi, 0.4, 1, 2/2, 1./3}

you can do:

And @@ (Head[#] === Real & /@ list)
(* False *)
$\endgroup$
3
$\begingroup$

You can use Element:

Element[{$x_1 , x_2 , \ldots$}, dom] asserts that all the $x_i$ are elements of dom.

Using mgamer's example list:

{Pi, 0.4, 1, 2/2, 1./3} ∈ Reals

True

The built-in mathematical constants:

{Catalan, °, E, EulerGamma, Glaisher, GoldenRatio, Khinchin, MachinePrecision, π} ∈ Reals

True

{Pi, 1 + I, 1, .5} ∈ Reals

False

$\endgroup$
  • $\begingroup$ Seeing your solution I recognize, that I misinterpreted the original question. There was no question about Reals... ;-) Sometimes I see, what I want to see ;-) $\endgroup$ – mgamer Jul 23 at 15:56
  • $\begingroup$ @mgamer, the original post was about reals:) $\endgroup$ – kglr Jul 23 at 17:10
  • $\begingroup$ :-)) Thank you! Reading the hidden comments is sometimes enlightening.... $\endgroup$ – mgamer Jul 24 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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