What's the best way to join two lists?

It is fine to use concat and that is even highly efficient in some cases (it is the recommended technique in 8.4 and before, and not too bad in later versions). However, your second option with lappend will not work at all, and the version with append will work, but will also be horribly inefficient.

Other versions that will work:

# Strongly recommended from 8.6.1 on
set first [list {*}$first {*}$second]
lappend first {*}$second

The reason why the first of those is recommended from 8.6.1 onwards is that the compiler is able to optimise it to a direct "list-concatenate" operation.


Examples

% set first {a b c}
a b c
% set second {1 2 3}
1 2 3
% set first [concat $first $second]; # #1 is correct
a b c 1 2 3
% set first {a b c}
a b c
% lappend first $second; # #2 is wrong: appends the whole `second` list to `first
a b c {1 2 3}

Discussion

I looked up the documentation, also experiment with some lists and found out that:

  1. Your first choice, concat is correct
  2. lappend does not work because it treats $second as one element, not a list
  3. append works, but you are treating your lists as string. I don't know what the implications are, but it does not communicate the intention that first and second are lists.

Tags:

Tcl