Position( list, elm )
Position( list, elm, after )
Position returns the position of the element elm, which may be an
object of any type, in the list list. If the element is not in the
list the result is
false. If the element appears several times, the
first position is returned.
The three argument form begins the search at position after+1, and
returns the position of the next occurence of elm. If there are no
more, it returns
It is much faster to search for an element in a set, because for sets,
which are always sorted (see Sets),
Position can use a binary search,
instead of the linear search used for ordinary lists. So if you have a
list for which you want to perform a large number of searches you may
consider converting it to a set with the function
Set (see Set).
gap> Position( [ 2, 2, 1, 3 ], 1 ); 3 gap> Position( [ 2, 1, 1, 3 ], 1 ); 2 gap> Position( [ 2, 1, 1, 3 ], 1, 2 ); 3 gap> Position( [ 2, 1, 1, 3 ], 1, 3 ); false gap> Position( [ 4, -1, 0, 3 ], 1 ); false gap> s := Set([2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32]);; gap> Position( s, 17 ); false # uses binary search and only 4 comparisons gap> Position( [ "This", "is", "a", "list", "of", "strings" ], 1 ); false gap> Position( [ [0,6], [0,4], [1,3], [1,5], [1,2], [3,4] ], [1,2] ); 5
in operator (see In) can be used if you are only interested to
know whether the element is in the list or not.
PositionSorted) can be used if the list is sorted.
(see PositionProperty) allows you to find the position of an element
that satisfies a certain property in a list.
Previous Up Top Next