# Declaring lists

Do I have to declare a list before using it in a loop?

for example:

For[i = 1, i < 10, i++, A[[i]] = i];


The output is:

Symbol A in part assignment does not have an immediate value


What is the proper way to do this?

• You need to initialize A first if you want your code to work as it is, e.g. like this: A = ConstantArray[Null, 9] or use. Better though to use Table or Array: Array[# &, 9]. – Yves Klett Dec 21 '15 at 18:04
• @jarhead, that is a useful article – garej Dec 21 '15 at 19:42

This is quite regular.

a = {};
For[i = 1, i < 10, i++, AppendTo[a, i]]


the result:

a


{1, 2, 3, 4, 5, 6, 7, 8, 9}

Otherwise you could do

a = ConstantArray[Null, 10 - 1];
For[i = 1, i < 10, i++, a[[i]] = i]


or

a = ConstantArray[Null, 10 - 1];
Array[(a[[#]] = #) &, 9]


Or simply using function variables:

Clear[a]

Array[(a[#] = #) &, 9]


but this does not give list a, although the elements can be referenced, e.g.

a[4]


4

Mathematica is not a declarative language. Don't expect to declare things.

Mathematica is clumsy as a procedural language, so avoid For[] loops.

Avoid using upper case to start your symbol names to prevent conflicts with the thousands of built-in symbols.

Use a functional programming approach:

a = Table[i, {i, 1, 10}]

Table[i,{i, 10}]


OR

Range @ 10


OR

RandomInteger[100,10]


OR

RandomReal[1,10]


If you just want to generate a list you can use a set of functions such as: Table, Range, RandomInteger, RandomReal etc.

Also see associated tutorial for list generation: Link

• You missed the point, the calculation for A[[i]] is just an example....I have there a more complicated calculation – jarhead Dec 22 '15 at 12:06
• @jarhead I do apologise. – e.doroskevic Dec 22 '15 at 12:11
• but thanks for the info though – jarhead Dec 22 '15 at 12:15
• @jarhead glad you found it useful! – e.doroskevic Dec 22 '15 at 12:19