This dirty code simulates the function "array_pad" of other languages for example PHP (more info in array_pad on php )
proc array_pad { _arr size value} {
foreach {a b} $_arr {
lappend arr "$a $b"
}
set orig_len [llength $arr]
set diff [expr abs($size) - $orig_len];
if { $diff <= 0 } {
return $_arr
}
if {$size < 0 } {
set idx 0
set sign -1
} else {
set idx [expr $orig_len-1];
set sign 1
}
set pointer [ lindex [lsort -integer -index 0 $arr] "$idx 0"]
for {set j 0 } {$j < $diff} {incr j} {
set pointer [expr $pointer+$sign]
lappend _arr $pointer $value
}
return $_arr
}array set arr {0 12 1 10 2 9};
set larr [array get arr]
array set arr1 [array_pad $larr 5 0];
parray arr1
# PHP'esque (12, 10, 9, 0, 0)
array set arr2 [array_pad $larr -7 -1];
parray arr2
# (-1, -1, -1, -1, 12, 10, 9)
array set arr3 [array_pad $larr 2 "noop"];
parray arr3
# not paddedAMB - 2025-05-30 18:29:19
The package ndlist has a function called "npad" which is similar, but for n-dimensional lists. As of v0.12, I haven't implemented padding that prepends the elements, so that is something I may want to implement.
package require ndlist
namespace import ndlist::npad
# 1D list
set x {1 2 3}
puts [npad $x 0 2]; # 1 2 3 0 0
# 2D list
set x {{1 2} {3 4} {5 6}}
puts [npad $x 0 {1 3}]; # {1 2 0 0 0} {3 4 0 0 0} {5 6 0 0 0} {0 0 0 0 0}