Message Boards Message Boards

0
|
2819 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

[?] Use Do loop to swap each element in a list?

Posted 7 years ago

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!

POSTED BY: Siyad Hams

temp[i] means "apply the function temp to the argument i". Temp in your case is a list, not a function so you get an error.

temp[[i]] means "the ith element of the list temp"

Your confusion is that other languages (such as C) uses temp[i] to index an array. This is not the syntax for Mathematica.

Hope this helps

Regards

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract