# append

Definition: | sequence s2 = append(object s1, object x)
Description: | Create a new sequence identical to s1 but with x added on the end as the last element. The length of s2 will be always be one more than length(s1), unless s1 is an atom, in which case the length of s2 will be 2.
pwa/p2js: | Supported.
Comments: | If x is an atom this is the same as `s2 = s1 & x`. If x is a sequence it is definitely not the same. Although s1 is typically a sequence, and historically it had to be, it can now also be an atom, which can simplify certain algorithms. The extra storage is allocated automatically and very efficiently with Phix’s dynamic storage allocation. The case where s1 and s2 are actually the same variable (as in Example 1 below) is highly optimized. TIP: append is ideally suited to adding an element (and always exactly one element) to a (sequence which represents a) list or table. When constructing strings, concatenation ('&') should be used instead - even though append() is technically valid in some character-by-character cases, concatenation makes the intent clearer. Also note that concatenation must be used when the intent is to add "zero, one, or more" elements (or characters) to a list or table (or string), in a single operation. It is also fair to say that s = append(s,expr) produces the same results as s &= {expr}, and in fact the compiler should emit exactly the same binary, not so prepend since it’s quite a tricky mapping, or the JavaScript as emitted by pwa/p2js, though actual results should match.
Example 1: | You can use append() to dynamically grow a sequence, e.g.
    sequence x
    x = {}
    for i=1 to 10 do
        x = append(x, i)
    end for
    -- x is now {1,2,3,4,5,6,7,8,9,10} (or use tagset(10))
Example 2: | Any kind of Phix object can be appended to a sequence, e.g.
    sequence x, y, z
    x = {"fred", "barney"}
    y = append(x, "wilma")
    -- y is now {"fred", "barney", "wilma"}
    z = append(append(y, "betty"), {"bam", "bam"})
    -- z is now {"fred", "barney", "wilma", "betty", {"bam", "bam"}}
Example 3: | Watch out for this common mistake:
    append({1,2,3}, {4,5})   -- {1, 2, 3, {4,5}}
    append("abc", "de")      -- {'a','b','c',"de"}
    -- Compare with concatenation:
    {1,2,3} & {4,5}          -- {1, 2, 3, 4, 5}
    "abc" & "de"             -- "abcde"
Implementation: | via :%opApnd in builtins\VM\pApnd.e (an autoinclude) - be warned however it is low-level complicated stuff that you do not need to know.
See Also: | prepend, concatenation operator &, sequence-formation operator, tagset