Skip to content
Tcl Source Code Artifact [9d622f956d]
Login

Artifact [9d622f956d]

Artifact 9d622f956d11b6f0af1bdf19b5e22fad1f75b2aaef8a998c0205686fb2d6a834:



CommandName: lreplace ManualSection: n Version: 7.4 TclPart: Tcl TclDescription: Tcl Built-In Commands Links:

Name

lreplace - Replace elements in a list with new elements

Synopsis

::: {.synopsis} ::: [lreplace]{.cmd} [list]{.arg} [first]{.arg} [last]{.arg} [element element]{.optdot} :::

Description

lreplace returns a new list formed by replacing zero or more elements of fIlistfR with the fIelementfR arguments. fIfirstfR and fIlastfR are index values specifying the first and last elements of the range to replace. The index values fIfirstfR and fIlastfR are interpreted the same as index values for the command fBstring indexfR, supporting simple index arithmetic and indices relative to the end of the list. 0 refers to the first element of the list, and fBendfR refers to the last element of the list.

If either fIfirstfR or fIlastfR is less than zero, it is considered to refer to before the first element of the list. This allows fBlreplacefR to prepend elements to fIlistfR. If either fIfirstfR or fIlastfR indicates a position greater than the index of the last element of the list, it is treated as if it is an index one greater than the last element. This allows fBlreplacefR to append elements to fIlistfR.

If fIlastfR is less than fIfirstfR, then any specified elements will be inserted into the list before the element specified by fIfirstfR with no elements being deleted.

The fIelementfR arguments specify zero or more new elements to be added to the list in place of those that were deleted. Each fIelementfR argument will become a separate element of the list. If no fIelementfR arguments are specified, then the elements between fIfirstfR and fIlastfR are simply deleted.

Examples

Replacing an element of a list with another:

% lreplace {a b c d e} 1 1 foo
a foo c d e

Replacing two elements of a list with three:

% lreplace {a b c d e} 1 2 three more elements
a three more elements d e

Deleting the last element from a list in a variable:

% set var {a b c d e}
a b c d e
% set var [lreplace $var end end]
a b c d

A procedure to delete a given element from a list:

proc lremove {listVariable value} {
    upvar 1 $listVariable var
    set idx [lsearch -exact $var $value]
    set var [lreplace $var $idx $idx]
}

Appending elements to the list; note that fBend+2fR will initially be treated as if it is fB6fR here, but both that and fB12345fR are greater than the index of the final item so they behave identically:

% set var {a b c d e}
a b c d e
% set var [lreplace $var 12345 end+2 f g h i]
a b c d e f g h i