36

What's a simple way to check if an item is in a list?

Something like

(in item list)

might return true if item=1 and list=(5 9 1 2) and false if item=7

River
  • 8,585
  • 14
  • 54
  • 67
Jeff
  • 12,147
  • 10
  • 51
  • 87

3 Answers3

48

Common Lisp

FIND is not a good idea:

> (find nil '(nil nil))
NIL

Above would mean that NIL is not in the list (NIL NIL) - which is wrong.

The purpose of FIND is not to check for membership, but to find an element, which satisfies a test (in the above example the test function is the usual default EQL). FIND returns such an element.

Use MEMBER:

> (member nil '(nil nil))
(NIL NIL)  ; everything non-NIL is true

or POSITION:

> (numberp (position nil '()))
NIL
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
22

Use MEMBER to test whether an item is in a list:

(member 1 '(5 9 1 2))  ; (1 2)

Unlike FIND, it is also able to test whether NIL is in the list.

Terje Norderhaug
  • 3,649
  • 22
  • 25
  • 1
    I do not really like this advise as it is. member returns the list from the position on where the element is found. The question asks for something like a predicate, returning either `T` or `NIL`. Hence I suggest this answer should be wrapped in an `if` and all that defined as the function anyone reading this page is looking for: `(defun contains (item sequence) (if (member item sequence) T NIL))` – BitTickler Aug 16 '20 at 12:31
10

You can use find:

(find 1 '(5 9 1 2)) ; 1
(find 7 '(5 9 1 2)) ; nil

Consider using :test argument:

(find "a" '("a" "b") :test #'equal)
khachik
  • 28,112
  • 9
  • 59
  • 94