I was wondering how to check if an element is in a list. I have the following function defined in a file:

let g:some_list = ["a", "b", "c", "d", "e", "f", "g", "h"]

function! Test(item)
    if a:item in g:some_list
        echo "Yes"
        echo "No"

After sourcing the file I called the function with :call Test("a"). It shows the following error:

Error detected while processing function Test:
line    1:
E15: Invalid expression: a:item in g:some_list

So in regard to the invalid expression, the question is how do I check if an item is in a list? Couldn't find anything in :help if, :help list.

  • If you do :h list and then scroll down until you see List functions (or go directly to :h Dictionary and scroll a page up). Also Please see :h list-functions and :h function-list Sep 10, 2020 at 8:52
  • 1
    if count(g:some_list, a:item) > 0 works. Not sure if this is best way.
    – mahbubweb
    Sep 10, 2020 at 9:03

2 Answers 2


index() can be used to check whether or not an item is in a list.

The body of your function should be written like this:

if index(g:some_list, a:item) >= 0  " If item is in the list.
    echo "Yes"
    echo "No"

To check that the item is not in the list, use index(g:some_list, a:item) == -1 instead.


I think that index() would be the most efficient way for a strict equality. There is match() when pattern matching is required IIRC.

As Christian said, :h list-functions is a perfect place to start. Still many list related functions are missing. Over the years I've defined the one I'm missing in my library plugin: https://github.com/LucHermitte/lh-vim-lib/blob/master/autoload/lh/list.vim

Note that since then, some functions now exist -- but we can not assume they exist for each version of Vim :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.