Reputation: 13
Please rather close or down this post try to teach and help me to understand
As a newbie I have a very hard time to understand the following for loop
code in Julia
. I am sure this should be the same concept in other languages.
I would highly appreciate someone please in details explain to me why the following code for the mylist[3]
would be 23
mylist = [3, 2, 1]
count=3
for i in mylist
mylist[i]=count
count=count+10
end
mylist[3] = 23
If you Know a good textbook/source/course to help me please let me know.
Upvotes: 0
Views: 92
Reputation: 5600
First loop: count=3 so mylist[3]=3 then count=13
Second loop: count=13 so mylist[2]=13 then count=23
Final loop: count=13 so mylist[3]=23 Since third element in mylist is changed to 3 in first loop.
Thus you get 23
Upvotes: 1
Reputation: 19132
Just walk through the example. You're looping through the values of mylist
, so the first i
is 3. Therefore mylist[i]=count
makes mylist[3]=3
. count=count+10
updates count
to be 13
. The second time through mylist
makes mylist[2]=13
and then count=23
. Then, since the first round made mylist[3]=3
, we have i=3
in the last round, which sets mylist[i]=count
which is now 23
. Thus mylist[3]=23
.
Use the REPL to walk through it yourself and it'll be more clear. Going step by step like this is a good way to understand code.
Upvotes: 4