Re: Identical elements
- To: mathgroup at smc.vnet.net
- Subject: [mg88404] Re: Identical elements
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Mon, 5 May 2008 06:08:40 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <fvhe2h$3th$1@smc.vnet.net>
KFUPM wrote: > I have a list and i need to test whether all the elements in the list > are identical or no. What is the efficient way to do that? The output > should be true if all elements are the same and False otherwise. One > line command is preferred if possible. > > Your help is highly appreciated. A possible approach, thought you did precise neither the type of the elements of the list (numeric, symbolic, mixed,...) nor whether the list could contains some other lists, is the following. We test each remaining element of the list against the first element and return False as soon as an element differs from the first one. myCheck[lst_List] := Module[{fe = First@lst, status = True}, Scan[If[# != fe, Return[status = False]] &, Rest@lst]; status] myCheck[{1, 1, 1, 1}] myCheck[{1, 1, -1, 1}] myCheck[{{1, 2}, {1, 2}, {1, 2}, {1, 2}}] myCheck[{{1, 2}, {1, 2}, {-1, 2}, {1, 2}}] True False True False Regards, -- Jean-Marc