# How to check whether the given value belongs to the list?

Consider some list

list={1.2,1.6,1.8,1.9,2,2.22,3.04,1000};


I would like to check whether some parameter x belongs to the values of the list, and if it does, then return parameter^2, while if it does not, then return 0. Could you please tell me how to do this?

• f = Boole@MemberQ[list, #]*#^2 & Jan 13 at 15:48

There are few way. One could be to use MemberQ with an If

list = {1.2, 1.6, 1.8, 1.9, 2, 2.22, 3.04, 1000};
x = 1.6;
If[MemberQ[list, x], x^2, 0]


Try this:

check[x_] := If[MemberQ[lst, x], x^2, 0]


Let us test it:

lst = {1.2, 1.6, 1.8, 1.9, 2, 2.22, 3.04, 1000};

check[1.9]

(*  3.61 *)

check[1.8]

(*  3.24  *)

check[1.7]

(*  0 *)


Done. Have fun!

f = #^2 Unitize@Length@Cases[alist, #] &


For testing:

tList = RandomReal[{-10, 10}, {10}]~Join~alist~Join~
RandomInteger[{-10, 10}, {10}]

f /@ tList

{0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.44, 2.56, 3.24, 3.61, 4, \
4.9284, 9.2416, 1000000, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0}