This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Practical Introduction / Lists  /

1.8.5 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 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]


  • Count counts the number of occurrences of a.
  • In[2]:= Count[{a, b, c, a, b}, a]


  • This shows that a is an element of {a,b,c}.
  • In[3]:= MemberQ[{a, b, c}, a]


  • On the other hand, d is not.
  • In[4]:= MemberQ[{a, b, c}, d]


  • This assigns m to be the

    identity matrix.
  • In[5]:= m = IdentityMatrix[3]


  • This shows that 0 does occur somewhere in m.
  • In[6]:= FreeQ[m, 0]


  • This gives a list of the positions at which 0 occurs in m.
  • In[7]:= Position[m, 0]


  • Extract takes the list of positions and shows that the element at each position is indeed 0.
  • In[8]:= Extract[m, %]


    As discussed in Section 2.3.2, 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".