How to get value from a list in Tcl?

30,264

Solution 1

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.

Solution 2

Just do

lindex $list 2

you will get

0x3

Solution 3

You "should" be using lindex for that. But from your question I have te impression that you do not want the "," to be present in the element extracted. You don't need the "," to separate the list. Just the blank space will do.

> set list1 {0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9}
> 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9
> lindex $list1 3
> 0x4
Share:
30,264
user2131316
Author by

user2131316

Updated on September 07, 2020

Comments

  • user2131316
    user2131316 almost 4 years

    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?

  • user2131316
    user2131316 over 10 years
    are there any index in the list, can we get the second element? or in this case, should we use array?
  • user2131316
    user2131316 over 10 years
    what you mean by a foreach for pairs of values? and one value and one index for array or list?
  • Jerry
    Jerry over 10 years
    @user2131316 What are you exactly trying to do? Update your question accordingly please. This is getting confusing :(