user2131316
user2131316

Reputation: 3287

How to get value from a list in Tcl?

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?

Upvotes: 6

Views: 47407

Answers (3)

thiago
thiago

Reputation: 23

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

Upvotes: 1

Sagar Shahabade
Sagar Shahabade

Reputation: 91

Just do

lindex $list 2

you will get

0x3

Upvotes: 8

Jerry
Jerry

Reputation: 71598

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.

Upvotes: 9

Related Questions