How to check if list item exists in TCL?

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

To check if a list item exists at the location indicated by the index I 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 the seams won't work. How am I supposed to do this? properly? It’s okay to check if {[lindex $ myList 6]] eq ""}

+8
source share
3 answers

I found this question because I wanted to check if the list contains a specific element, and not just check the length of the list.

To find out if an item exists in the list, use the function lsearch:

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

lsearch -1, . -exact, -glob ( ) -regexp .

+7

llength :

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

, , lindex . if {[lindex $myList 6] == "something"}

info exists , info exists , . , , , , [lindex $myList 6].

+15

TCL - "in", :

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

/ !

0

All Articles