Constructing Lists

Lists are widely used in the Wolfram Language, and there are many ways to construct them.

Some explicit ways to construct lists.

This gives a table of the first five powers of 2:

Table[2^i,{i,5}]

Here is another way to get the same result:

Array[2^#&,5]

This gives a similar list:

NestList[2#&,1,5]

(RefLink[SparseArray, paclet:ref/SparseArray]) lets you specify values at particular positions:

Normal[SparseArray[{3->x,4->y},5]]

You can also use patterns to specify values:

Normal[SparseArray[{i_->2^i},5]]

Often you will know in advance how long a list is supposed to be, and how each of its elements should be generated. And often you may get one list from another.

Constructing lists from other lists.

This selects elements less than 5:

Select[{1,3,7,4,10,2},#<5&]

This takes elements up to the first element that is not less than 5:

TakeWhile[{1,3,7,4,10,2},#<5&]

This explicitly gives numbered parts:

{a,b,c,d}[[{2,1,4}]]

This picks out elements indicated by a 1 in the second list:

Pick[{a,b,c,d},{1,0,1,1},1]

Sometimes you may want to accumulate a list of results during the execution of a program. You can do this using (RefLink[Sow, paclet:ref/Sow]) and (RefLink[Reap, paclet:ref/Reap]).

Using (RefLink[Sow, paclet:ref/Sow]) and (RefLink[Reap, paclet:ref/Reap]).

This program iteratively squares a number:

Nest[#^2&,2,6]

This does the same computation, but accumulating a list of intermediate results above 1000:

Reap[Nest[(If[#>1000,Sow[#]];#^2)&,2,6]]

An alternative but less efficient approach involves introducing a temporary variable, then starting with t={}, and successively using (RefLink[AppendTo, paclet:ref/AppendTo])[t,elem].