Constructing Lists
Lists are widely used in the Wolfram Language, and there are many ways to construct them.
Range[n] | the list {1,2,3,…,n} |
Table[expr,{i,n}] | the values of expr with i from 1 to n |
Array[f,n] | the list {f[1],f[2],…,f[n]} |
NestList[f,x,n] | {x,f[x],f[f[x]],…} with up to n nestings |
Normal[SparseArray[{i1->v1,…},n]] | a length n list with element ik being vk |
Apply[List,f[e1,e2,…]] | the list {e1,e2,…} |
Some explicit ways to construct lists.
SparseArray lets you specify values at particular positions.
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.
Table[expr,{i,list}] | the values of expr with i taking on values from list |
Map[f,list] | apply f to each element of list |
MapIndexed[f,list] | give f[elem,{i}] for the ielement |
Cases[list,form] | give elements of list that match form |
Select[list,test] | select elements for which test[elem] is True |
Pick[list,sel,form] | pick out elements of list for which the corresponding elements of sel match form |
TakeWhile[list,test] | give elements ei from the beginning of list as long as test[ei] is True |
list[[{i1,i2,…}]] or Part[list,{i1,i2,…}] | |
give a list of the specified parts of list |
Constructing lists from other lists.
Sometimes you may want to accumulate a list of results during the execution of a program. You can do this using Sow and Reap.
Sow[val] | sow the value val for the nearest enclosing Reap |
Reap[expr] | evaluate expr, returning also a list of values sown by Sow |
An alternative but less efficient approach involves introducing a temporary variable, then starting with t={}, and successively using AppendTo[t,elem].