Mathematica 9 is now available
Previous section-----Next section

1.8.5 Testing and Searching List Elements

Position[list, form] the positions at which form occurs in list
Count[list, form] the number of times form appears as an element of list
MemberQ[list, form] test whether form is an element of list
FreeQ[list, form] test whether form occurs nowhere in list

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]

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[4]:=  MemberQ[{a, b, c}, d]

Out[4]=

This assigns m to be the  identity matrix.

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

Out[5]=

This shows that 0 does occur somewhere in m.

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

Out[6]=

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

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

Out[7]=

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".



Any questions about topics on this page? Click here to get an individual response.Buy NowMore Information
THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT.
SEE THE DOCUMENTATION CENTER FOR THE LATEST INFORMATION.