I am currently studying the functional programming part of Mathematica. But I am very confused right now about what I have learned so far.
This because I saw an example when reading <Programming with Mathematica an Introduction > by Paul Wellin using Do
loop to swap list elements.
For example, original list :
lis = {{a, 1}, {b, 2}, {c, 3}}
Desired Result should be:
{{1, a}, {2, b}, {3, c}}
I try to write the program code as below but got errors
lis = {{a, 1}, {b, 2}, {c, 3}};
temp={0,0,0};
Do[temp[i] = {lis[[i, 2]], lis[[i, 1]]}, {i, 1, Length[lis]}];
temp
Errors:
Set::write: Tag List in {{1,a},{2,b},{3,c}}[1] is Protected.
Set::write: Tag List in {{1,a},{2,b},{3,c}}[2] is Protected.
Set::write: Tag List in {{1,a},{2,b},{3,c}}[3] is Protected.
General::stop: Further output of Set::write will be suppressed during this calculation.
For fixing this issue,The textbook use part expression to run this code , but I don't understand why temp[[i]]
instead of temp[i]:
Do[temp[[i]] = {lis[[i, 2]], lis[[i, 1]]}, {i, 1, Length[lis]}];
So I will really appreciate anyone could clarify this. Thanks!