Pick

Pick[list,sel]

picks out those elements of list for which the corresponding element of sel is True.

Pick[list,sel,patt]

picks out those elements of list for which the corresponding element of sel matches patt.

Details

  • sel can be a nested list of any depth.
  • Pick[list,sel,patt] picks out those list[[i1,i2,]] for which sel[[i1,i2,]] matches patt.
  • Depending on the arrangement of elements matching patt in a nested list sel, Pick may return a ragged array.
  • The heads in list and sel do not have to be List.
  • Pick works with SparseArray objects.

Examples

open allclose all

Basic Examples  (2)

Pick out elements wherever a 1 appears in the "selector" list:

Pick out elements from a 2D array:

Scope  (4)

Pick out elements wherever True appears in the "selector" list:

Pick elements whose parts match a pattern:

Use a SparseArray to select arguments:

Pick elements from a SparseArray:

Generalizations & Extensions  (3)

The data does not have to be a list:

The selector argument need not be a list:

Convert strings to a list of characters to pick only certain characters:

Properties & Relations  (1)

The comparison in Pick[list,sel,patt] is purely structural, with no regard to heads:

f[b] is selected because the 3,1 part of sel matches the patt:

The corresponding part of list, if it exists, will be picked, along with its heads:

Note that the 2,1 part of sel also matches patt:

However, there is no corresponding part of list to be picked:

Possible Issues  (4)

The "selector" list has to have the same length and structure as the data:

Atomic expressions are allowed in Pick:

This is because all partsincluding the empty partare tested for matching:

If there is an atomic argument and it is not picked in its entirety, Sequence[] is returned:

This applies equally to the second argument:

Using Except[c] in the third argument can lead to unexpected results:

The whole expression is returned because the entire selector argument matches the pattern:

Use Except[c,p] to restrict the pattern to elements of the selector argument:

Using nonatomic expressions in the selector argument can lead to unexpected results:

Applying the test beforehand so the list only contains True and False avoids the structure issue:

Introduced in 2004
 (5.1)