Search code examples
tcl

What's the best way to join two lists?


I have two lists that contain some data (numeric data or/and strings)?

How do I join these two lists, assuming that the lists do not contain sublists?

Which choice is preferred and why?

  1. set first [concat $first $second]

  2. lappend first $second

  3. append first " $second"


Solution

  • 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.