the_meter413
the_meter413

Reputation: 299

Tcl/tk: should I use for or foreach?

I have three lists that I'd like to iterate through so that I evaluate each permutation of variables in my lists. I currently have a for loop with two nested for loops, but I'm wondering if I can achieve the same with a foreach? I can't quite figure out the foreach syntax, however. (Probably because I don't have a firm grasp of how/when to use foreach).

Here's my current block of code. Is it possible to write this as a foreach?

set list1 {a b c}
set list2 {red blue green}
set list3 {dogs cats chickens}

for {set i 0} {$i < [llength $list1]} {incr i} {
   for {set j 0} {$j < [llength $list2]} {incr j} {
      for {set k 0} {$k < [llength $list3]} {incr k} {
         set alpha [lindex $list1 $i]
         set color [lindex $list2 $j]
         set animal [lindex $list3 $k]
         puts "$alpha $color $animal"
      }
   }
}

Upvotes: 1

Views: 856

Answers (1)

Jerry
Jerry

Reputation: 71538

You can use foreach instead of for when you are iterating through a list and you don't need the indices, but rather the elements of the list themselves. For example, you could use the following instead of your current loops:

foreach alpha $list1 {
   foreach color $list2 {
      foreach animal $list3 {
         puts "$alpha $color $animal"
      }
   }
}

Please do take a look at the manual on foreach.

Upvotes: 4

Related Questions