48

How do you check, in elisp, if a list contains a value? so the following would return t:

(contains 3 '(1 2 3))

but

(contains 5 '(1 2 3))

would return nil.

Stefan
  • 27,908
  • 4
  • 53
  • 82
Nathaniel Flath
  • 15,477
  • 19
  • 69
  • 94

2 Answers2

79

The function you need is member

For example:

(member 3 '(1 2 3))

It will return the tail of list whose car is element. While this is not strictly t, any non-nil value is equivalent to true for a boolean operation. Also, member uses equal to test for equality, use memq for stricter equality (using eq).

Stefan
  • 27,908
  • 4
  • 53
  • 82
freiksenet
  • 3,569
  • 3
  • 28
  • 28
  • 1
    For further details, see http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/List-Processing.html – viam0Zah Sep 11 '09 at 13:14
8

freiksenet's answer is good and idiomatic. If you are using dash.el, you could also call function -contains?, which does exactly the same—checks if some list contains an element:

(-contains? '(1 2 3) 2) ; t
Community
  • 1
  • 1
Mirzhan Irkegulov
  • 17,660
  • 12
  • 105
  • 166