3

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"
    else
        echo "No"
    endif
endfunction

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.

2
  • 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 – Christian Brabandt Sep 10 '20 at 8:52
  • if count(g:some_list, a:item) > 0 works. Not sure if this is best way. – Mahbub Alam Sep 10 '20 at 9:03
6

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 :(

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"
else
    echo "No"
endif

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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