How to check if list element exists in TCL?

Narek picture Narek · Apr 11, 2011 · Viewed 33.2k times · Source

Say I have a TCL list, and I have append some elements to my list. Now I want to check if I have appended 6 or 7 elements.

In order to check if list element exists in the place specified by an index I have used:

if { [info exists [lindex $myList 6]] } {
#if I am here then I have appended 7 elems, otherwise it should be at least 6
}

But seams this does not work. How I should do that? properly? It is OK to check if { [lindex $myList 6]] eq "" }

Answer

überjesus picture überjesus · Apr 11, 2011

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].