Legacy Documentation

Mathematica® Teacher's Edition (2002)

This is documentation for an obsolete product.
Current products and services
 Documentation /  Mathematica Teacher's Edition /  The Teacher's Book /  Interlude 1: Lists /

12.4 Testing and Searching List Elements

Testing and searching for elements of lists.

The previous section discussed how to extract pieces of lists based on their positions or indices. Mathematica TE also has functions that search and test for elements of lists, based on the values of those elements.

This gives a list of the positions at which a appears in the list.

In[1]:= Position[{a, b, c, a, b}, a]

Out[1]=

Count counts the number of occurrences of a.

In[2]:= Count[{a, b, c, a, b}, a]

Out[2]=

This shows that a is an element of {a, b, c}.

In[3]:= MemberQ[{a, b, c}, a]

Out[3]=

On the other hand, d is not in the list.

In[4]:= MemberQ[{a, b, c}, d]

Out[4]=

This assigns m to be the identity matrix, a list of lists.

In[5]:= m = IdentityMatrix[3]

Out[5]=

The sublist {0, 1, 0} is an element of m.

In[6]:= MemberQ[m, {0, 1, 0}]

Out[6]=

But 0 is not an element of m.

In[7]:= MemberQ[m, 0]

Out[7]=

This shows that 0 does occur somewhere in m.

In[8]:= FreeQ[m, 0]

Out[8]=

This gives a list of the three positions at which 1 occurs in m.

In[9]:= Position[m, 1]

Out[9]=

The functions Count and Position, as well as MemberQ and FreeQ, can be used not only to search for particular list elements, but also to search for classes of elements which match specific "patterns". This is discussed in Section 27.2.