Selecting Member of a List

There are a few other functions that are useful in manipulating lists. These allow us Select
elements of a list satisfying a specified condition. The following four functions are important.

MemberQ[ list, element] returns True if the element occurs in the list.

Select[ list, condition] returns a list of elements of list satisfying the condition

Position[ list, element] returns a list of all places that the element occurs in the list.

Count[ list, element] returns the number of occurrences of element in list.


Suppose we wish to select primes from a list of integers. Then we can use Select with
PrimeQ.

In[42]:=

  Select[ { 3, 7, 9, 17, 127, 315}, PrimeQ]

Out[42]

In[43]:=

  MemberQ[ { 3,7,8, 9, 11}, 9]

Out[43]

In[44]:=

  Position[ { 3, 7, 7, 8, 9, 7, 8, 0}, 7]

Out[44]

Exercise: Write a function to make a list of numbers of the form 5k+3 that are prime.
Write another function to make a list of numbers of the form 7k+1 that are squarefree.
You can use the function squarefreeQ that was written in the previous section.

Exercise: Recall that we had a function squareQ that checks if a number is a perfect
square by computing its real square root, taking the integer part, squaring it again to see
if it equals the number. This is inefficient, and can be made more efficient by checking
the remainder when divided by different integers. For example, a perfect square that
is divided by 16 has a remainder of 0, 1, 4, or 9. Use this fact to write a function
newsquareQ that first checks if Mod[ n, 16] is in the list { 0,1,4,9} before
applying the older test. This will eliminate the square root computation is 3/4 of the inputs.

Up to Lists