Reputation: 1
I have a list of this form {a b} and I cannot insert anything inside the curly brackets
I tried these:
set csv [list]
lappend csv [list \
a \
b]
set csv [linsert $csv 1 x]
puts "$csv" # OUTPUT {a b} x
###############
set csv [list]
lappend csv [list \
a \
b]
set csv [linsert $csv [llength $csv] x y]
puts "$csv" # OUTPUT {a b} x y
###############
set csv2 [list]
lappend csv2 [list \
a \
b]
lappend csv2 [list x y]
puts "$csv2" # OUTPUT {a b} {x y}
###############
set csv2 [list]
lappend csv2 [list \
a \
b]
lappend csv2 y
puts "$csv2" #OUTPUT {a b} y
The part with "lappend csv [list " exists there since 2016 and I don't want to change. I just need to append something inside the curly braces so the desired output will be {a b x y}
Upvotes: 0
Views: 45
Reputation: 4813
The command lappend csv [list a b]
adds a single element to the list. Since you started with an empty list, you will have a list consisting of a single element, which in turn is a list.
Now you want to insert more elements into that sublist, rather than into the overall list. The linsert
and lappend
commands only work on a straight forward list. They cannot reach into sublists on their own. So you will have to extract the sublist, modify it, and then put it back:
lset csv 0 [linsert [lindex $csv 0] 1 x y]
As a special case, you can take advantage of some features of lset
if you only need to append a single element to the end of the sublist: The lset
command can reach into sublists and it will add an element if the index exceeds the length of the list. So you can do:
lset csv 0 end+1 x
To end up with {a b x}
Upvotes: 1