TIP 421: A Command for Iterating Over Arrays

Bounty program for improvements to Tcl and certain Tcl packages.
Tcl 2019 Conference, Houston/TX, US, Nov 4-8
Send your abstracts to [email protected]
or submit via the online form by Sep 9.
State:		Final
Type:		Project
Tcl-Version:	8.7
Vote:		Done
Author:		Karl Lehenbauer <[email protected]>
Author:		Brad Lanam <[email protected]>
Author:		Donal K. Fellows <[email protected]>
Created:	28-Nov-2012
Updated:	24-Oct-2017
Against:	none
Present:	none
Tcl-Branch:     tip-421


This TIP proposes an efficient mechanism for iterating over the contents of a large array.


Tcl currently provides three main mechanisms for iterating over the contents of an array, but none are quite perfect when dealing with a large array.

The authors propose that there be a new subcommand of array which allows for efficient iteration over an array's elements.

Proposed Change

There should be a new command, array for, that has this syntax:

array for {keyVar valueVar} arrayName body

This will iterate internally over the elements of the array called arrayName in array-iteration order (i.e., the same as that used by the other array subcommands), setting the variable keyVar to the name of the element and the variable valueVar to the content of the element before evaluating the script body. The result will be the empty string (excepting errors, return, etc.) and any contained break and continue will have their normal interpretation as loop control operations.

Modifying the array while this command is iterating over it will make the array for command terminate with an error once the current execution of body finishes.


Branch: tip-421 (Code is also available here within a comment, but that is not the definitive version.)

The implementation is no faster then using array names or array get, but uses much less memory.


Bounty #12, Bounty #27


This document has been placed in the public domain.