I have a list in Tcl as:
set list1 {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
then how could I get the element based on the index of list? for example:
I want to get the second element of this list? or the sixth one of this list?
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.
DESCRIPTION. The lindex command accepts a parameter, list, which it treats as a Tcl list. It also accepts zero or more indices into the list. The indices may be presented either consecutively on the command line, or grouped in a Tcl list and presented as a single argument.
Lappend is similar to append except that the values are appended as list elements rather than raw text. This command provides a relatively efficient way to build up large lists. For example, ``lappend a $b'' is much more efficient than ``set a [concat $a [list $b]]'' when $a is long.
The lrange Command The third argument is the index of the last element of the range (so to select one element, the second index should be the same as the first). If the second index is the string end , the range extends to the end of the list.
Just use split and loop?
foreach n [split $list1 ","] {
puts [string trim $n] ;# Trim to remove the extra space after the comma
}
[split $list1 ","]
returns a list containing 0x1 { 0x2} { 0x3} { 0x4} { 0x5} { 0x6} { 0x7} { 0x8} { 0x9}
The foreach
loop iterates over each element of the list and assign the current element to $n
.
[string trim $n]
then removes trailing spaces (if any) and puts prints the result.
EDIT:
To get the nth element of the list, use the lindex
function:
% puts [lindex $list1 1]
0x2
% puts [lindex $list1 5]
0x6
The index is 0-based, so you have to remove 1 from the index you need to pull from the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With