Mathematica 9 is now available
 Documentation /  Mathematica /  The Mathematica Book /  A Practical Introduction to Mathematica /  Lists /

Getting Pieces of ListsAdding, Removing and Modifying List Elements

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]

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

Extract takes the list of positions and shows that the element at each position is indeed 0.

In[8]:= Extract[m, %]

Out[8]=

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

Getting Pieces of ListsAdding, Removing and Modifying List Elements



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.