Getting List Elements: llength, lindex, and lrange

   

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 5.  Tcl Lists


Getting List Elements: llength, lindex, and lrange

The llength command returns the number of elements in a list.

 llength {a b {c d}"e f g" h} => 5 llength {} => 0 

The lindex command returns a particular element of a list. It takes an index; list indices count from zero.

 set x {1 2 3} lindex $x 1 => 2 

You can use the keyword end to specify the last element of a list, or the syntax end-N to count back from the end of the list. The following commands are equivalent ways to get the element just before the last element in a list.

 lindex $list [expr {[llength $list] - 2}] lindex $list end-1 

The lrange command returns a range of list elements. It takes a list and two indices as arguments. Again, end or end-N can be used as an index:

 lrange {1 2 3 {4 5}}2 end => 3 {4 5} 

       
    Top
     



    Practical Programming in Tcl and Tk
    Practical Programming in Tcl and Tk (4th Edition)
    ISBN: 0130385603
    EAN: 2147483647
    Year: 1999
    Pages: 478

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net