27.14 In

elm in list

The in operator evaluates to true if the object elm is an element of the list list and to false otherwise. elm is an element of list if there is a positive integer index such that list[index]=elm is true. elm may be an object of an arbitrary type and list may be a list containing elements of any type.

It is much faster to test for membership for sets, because for sets, which are always sorted (see Sets), in 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 membership tests you may consider converting it to a set with the function Set (see Set).

    gap> 1 in [ 2, 2, 1, 3 ];
    true
    gap> 1 in [ 4, -1, 0, 3 ];
    false
    gap> s := Set([2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32]);;
    gap> 17 in s;
    false        # uses binary search and only 4 comparisons
    gap> 1 in [ "This", "is", "a", "list", "of", "strings" ];
    false
    gap> [1,2] in [ [0,6], [0,4], [1,3], [1,5], [1,2], [3,4] ];
    true 

Position (see Position) and PositionSorted (see PositionSorted) allow you to find the position of an element in a list.

Previous Up Top Next
Index

GAP 3.4.4
April 1997