How to iterate nested list in tcl?

tcl list
tcl list commands
tcl split list into variables
tcl flatten list
tcl list, length
tcl lappend
lrange in tcl
tcl check if list is empty

There is a nested list x in tcl

set x {{A 0} {B 1} {C 2} {D 3}}

How to iterate over and print all the elements in this nested list?

It's pretty easy to extend Dinesh's answer to make it truly recursive:

set x {{A 0} {B 1} {C 2} {D 3} {4 {F G}}}; # Have added one more element

proc printListElem {myList {level 1}} {
    foreach elem $myList {
        puts "[string repeat "+" $level] $elem"
        if {[llength $elem] > 1} {
            printListElem $elem [expr {$level + 1}]
        }
    }
}

printListElem $x

+ A 0
++ A
++ 0
+ B 1
++ B
++ 1
+ C 2
++ C
++ 2
+ D 3
++ D
++ 3
+ 4 {F G}
++ 4
++ F G
+++ F
+++ G

nested list, This video contains detailed description of nested lists and file handling in tcl. It also explains Duration: 5:21 Posted: 13 Nov 2018 The syntax for a nested while loop statement in Tcl language is as follows − while {condition} { while {condition} { statement(s); } statement(s); } A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. Example

If we know the list depth, we can just nest some foreach calls:

foreach a $x {
    foreach b $a {
        puts "--> $b"
    }
}

But a general "iterate over all possible nested lists" doesn't exist in Tcl, as the concept is incompatible with Tcl's type model. You literally shouldn't think about values in a way that makes that a sensible question to ask about. You don't build arbitrary trees: you build specific trees where the levels are meaningful to the problem at hand.

(The key problem is that red hot cat is simultaneously a 3 item list and an 11 character string.)

TCL lecture15 : Nested lists in TCL, In this chapter of the Tcl tutorial we cover Tcl lists and list related commands, including llength, Each loop cycle the item variable has the next value from the list of numbers. This is a simple example with nested lists in Tcl. The lmap command. It is possible to go through the list's elements with the lmap command. It is a functional command. The lmap command iterates over all elements in one or more lists and collects results.

set x {{A 0} {B 1} {C 2} {D 3} {6 {F G}}}

set y {{{{1 2 {3 4}}}}}

array set myarr {}
set count 0
proc printListElem {myList} {
    global myarr count
    for {set i 0} {$i <[llength $myList]} {incr i} {
        set currentElem [lindex $myList $i]
        if {![info exists myarr($count,${currentElem})]} {
            incr count
            set myarr($count,${currentElem}) 1
            printListElem $currentElem
        } else {
            incr count -1
            break
        }
    }
}

printListElem $y
foreach idx [lsort [array names myarr]] {
    lassign [split $idx ,] key value
    puts "[string repeat "+" $key]$value"
}

This one will work for all nested levels of lists and the output will be shown something like,

+{{1 2 {3 4}}}
++{1 2 {3 4}}
+++1 2 {3 4}
++++1
++++2
++++3 4
+++++3
+++++4

The number of + present in here will represent the nested level of list elements. (Thanks to Mr.Glenn for idea). This might not be an efficient, but it can be done in this way too.

Tcl lists, foreach — Iterate over all elements in one or more lists In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to� In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to assign to varname. The body argument is a Tcl script. For each element of list (in order from first to last), foreach assigns the contents of the element to varname as if the lindex command had been used to extract the element, then calls

I see people trying to iterate recursively and come up with generic solutions, and I'm pretty sure that some may not agree with this, but the answer to the question "How to iterate over and print all the elements in this nested list?" is pretty straightforward.

The list contains 4 elements "A 1", "B 2", "C 3", "D 4", so the answer would be:

% set x {{A 0} {B 1} {C 2} {D 3}}
{A 0} {B 1} {C 2} {D 3}

% foreach item $x {
    puts $item
}
A 0
B 1
C 2
D 3

Presuming that one would want to do something with the individual values then they can be split out using lindex or lassign, e.g.

% foreach item $x {
    lassign $item char num
    puts "char = $char, num = $num"
}
char = A, num = 0
char = B, num = 1
char = C, num = 2
char = D, num = 3

The foreach can also take multiple values so it would also be possible to do it this way:

foreach item $x {
    foreach {char num} $item {
        puts "char = $char, num = $num"
    }
}

In practice one wouldn't have random levels of nested lists to store useful data, but if one actually happens to have such data then it might be worth looking into dict.

As an example:

 % set x {A {B 2} C {D {E 5}} F 6}
 A {B 2} C {D {E 5}} F 6
 % dict get $x A
 B 2
 % dict get $x A B
 2
 % dict get $x C D E
 5
 % dict get $x F
 6

foreach manual page - Built-In Commands, NESTED LIST OPTIONS. These options are used to search lists of lists. They may be used with any other options. -index indexList: This option is� List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of items. It can include different types of items in the same list. Further, a list can contain another list.

If you are willing to completely lose all track of nesting levels then you can use this approach to completely collapse all nested list levels (except that if {} are used within a string value in the list those will also be obliterated

set x {{A 0} {B 1} {C 2} {D 3} {6 {F G}}} 
set xn [string map {"{" "" "}" ""} $x] 


puts [join $xn "\n"]

lsearch manual page - Tcl Built-In Commands, 5.2.1 Tcl Lists, Commands, Comments A Tcl command is a space-separated list of words. Of course, command expressions can be arbitrarily nested. proc computeAverage args { set result 0 foreach x $args { set result [expr $result + $x] }� In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to assign to varname. The body argument is a Tcl script. For each element of list (in order from first to last), foreach assigns the contents of the element to varname as if the lindex command had been used to extract the element, then calls

5.2 Introduction to Tcl, The foreach command implements a loop with the variable or variables assigned values from one or more lists and then performs an action. The list or lists may� tcl. Getting started with tcl; Control Structures; Dictionaries; Basic use of a dictionary; Iterating over a dictionary; List-appending to a nested dictionary; The dict get command can raise an error; Expressions; Pathnames and filenames; Procedure arguments; Regular Expressions; Tcl Language Constructs; Variables

Looping with foreach, Tcl - Nested Loops - Tcl allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. How to iterate nested list in tcl? 2. TCL: Nested Associative Arrays. 0. Dynamically Create Nested Lists in TCL. 0. TCL how to sort a nested dictionary by value. 1.

Tcl - Nested Loops, Tcl supports three types of loops, while, for, and foreach. for start test next body; But a general “iterate over all possible nested lists” doesn't exist in Tcl, as the� The list elements can be any string values, including numbers, variable names, file names, bits of Tcl code and other lists. The latter is possible because lists are just strings with a special interpretation that gives them structure. Lists may be nested to any depth, and are useful for representing trees, among other things. List Representation

Comments
  • What did you try and what is the expected output?
  • @Dinesh, do you want to take this in your answer?
  • Wow!!! It looks great. Better be a stand-alone wiki answer. :). Actually, I was thinking of making it to more robust by means of supporting more number of nested levels in list. Let me update it in my answer. Hope that it should be efficient.