Skip to content

lset

Sets an element in a list variable at a specified index, with support for nested lists.

Syntax

tcl
lset varName newValue
lset varName index newValue
lset varName index ?index ...? newValue

Parameters

  • varName: Name of the list variable (not the value)
  • index: Index of element to set. Supports:
    • Simple integers (e.g., 0, 1, 2)
    • The end keyword for the last element
    • Index arithmetic with + and - (e.g., end-1, end+0, 0+1)
    • Multiple indices for nested lists (e.g., 1 2 to access element 2 of the sublist at index 1)
    • Indices as a list (e.g., {1 2} is equivalent to 1 2)
    • Empty index list {} to replace the entire variable
  • newValue: New value for the element

Returns the modified list. The variable is modified in place.

Special Behaviors

  • When called with just varName newValue (no index), replaces the entire variable value
  • When called with an empty index list {}, also replaces the entire variable value
  • When the index equals the list length, the element is appended to the list
  • When accessing a nested index on a scalar, the scalar is treated as a single-element list

Error Conditions

  • Error if the variable does not exist
  • Error if the index is out of range (negative or greater than list length)
  • Error if the index format is invalid

Examples

Set element by index

Output

Set last element

Output

Set using end-relative index

Output

Modify in loop

Output

Returns new value

Output

Modify nested list

Output

Append element

When the index equals the list length, the element is appended:

Output

Replace entire variable

Using no index or an empty index list replaces the whole value:

Output

Index arithmetic

Indices support + and - arithmetic:

Output

See Also