How to check if list element exists in TCL?

Why don't you use llength to check the length of your list:

if {[llength $myList] == 6} {
    # do something
}

Of course, if you want to check the element at a specific index, then then use lindex to retrieve that element and check that. e.g. if {[lindex $myList 6] == "something"}

Your code using the info exists is not working, because the info exists command checks if a variable exists. So you are basically checking if there is a variable whose name equals the value returned by [lindex $myList 6].


Another way to check for existence in a list in TCL is to simply use 'in', for instance:

if {"4" in $myList} {
    puts "Found 4 in my list"
}

It's slightly cleaner/more readable!


I found this question because I wanted to check if a list contains a specific item, rather than just checking the list's length.

To see if an element exists within a list, use the lsearch function:

if {[lsearch -exact $myList 4] >= 0} {
    puts "Found 4 in myList!"
}

The lsearch function returns the index of the first found element or -1 if the given element wasn't found. Through the -exact, -glob (which is the default) or -regexp options, the type of pattern search can be specified.

Tags:

List

Exists

Tcl