I noticed that in Python it is possible to mimic while-loops using for-loops (I know very little about coding). I was then trying to construct two identical while-loops using the two different formulations. It seems to me that it is the case here (is it?)
# for-loop formulation
index = [0]
for a in index:
if a < 6:
index.append(a + 1)
# while-loop formulation
index = [0]
while index[-1] < 6:
index.append(index[-1] + 1)
What confuses me is that I thought that once the list index is updated/changed the for-loop would restart from the beginning, as the list could have changed dramatically at any cycle. For example if you run
#3
index = [0]
for a in index:
print a
if a < 6:
index.append(a+1)
if a > 3:
index = [1, 3]
print index
you get the output
0
[0, 1]
1
[0, 1, 2]
2
[0, 1, 2, 3]
3
[0, 1, 2, 3, 4]
4
[1, 3]
5
[1, 3]
where the a is not part of the new index [1, 3] in the last step. Hence three questions:
- Are the two programs #1 and #2 at the beginning different (for example, is their computational effort different?)
- What is happening in program #3 (why is the 'for a in index:' command apparently ignored in the last step?), and how does the for-loop react to changes in the updating index in general?
- Are there general guidelines on using for loops as while loops (I noticed that I found it helpful in a specific case, so I was wondering for some general tips in this direction).