5.6 How to build a LIST or a SET on the fly?

One way

L:=[]: 
for i from 1 to 3 do : 
    L:=[op(L),i]; 
end do;
 

But a better way is to use seq if one knows the length

L:=[seq(i,i=1..3)]; 
 
       L := [1, 2, 3]
 

Since list is immutable, a more efficient method, for long lists, is to use Array, and then convert the result back to list at the end since Array can grow dynamically without preallocation each time something is inserted as follows

L:=Array(): 
for i from 1 to 3 do : 
    L(i):=i; 
end do; 
 
for i from 1 to numelems(L) do : 
    print(L[i]); 
end do; 
 
L := convert(L,list)
 

Which will print

                            L := [1] 
 
                          L := [1, 2] 
 
                         L := [1, 2, 3] 
 
                               1 
 
                               2 
 
                               3 
 
                         L := [1, 2, 3]
 

Notice that to add to an Array, () is used. But to access an entry in an array [] is used.

And finally, using Array also, it can be done without using any indexing as follows

L:=Array(1..0): 
for i from 1 to 3 do : 
    L ,= i; 
end do; 
 
L := convert(L,list)
 

For the above to work, the array must be declared using Array(1..0). The new syntax  A ,= i  will append to the array, and there is no need to write  A(i) := i