Python - changing the variable inside for-loop gives different results

Viewed 211

When I try:

v = [1, 1]
for i in range(len(v)):
    v.append(1)
    print(v)

The output is:

[1, 1, 1]
[1, 1, 1, 1]

But when I do:

v = [1, 1]
for i in v:
    v.append(1)
    print(v)

It makes an infinite loop.

In both cases, the values of range(len(v)) and v should be changed inside the for-loop. Can someone explain why there are different results with those two similar codes?

When I further try a similar code in R and C++:

For R:

v <- c(1, 1)
for (i in v) v <- c(v, 1)
v <- c(1,1)
for (i in seq_along(v)) v<-c(v, 1)

For C++:

vector<int> v{1, 1};
for (auto i : v) v.push_back(1);

The resulting v is [1, 1, 1, 1], indicating that they have a similar behavior to Python's for i in range(len(v)):.

But in C++ (and Java):

vector<int> v{1, 1};
for (int i = 0; i < v.size(); i++) v.push_back(1);

produces an infinite loop, indicating that it has a similar behavior to Python's for i in v:. What is happening?

4 Answers

doing

for i in var:

means that the loop will run for each item in var then in the loop you append items to var creating an infinite loop

range(len(var))

however repeats the loop for the number of elements in var when the lopp is started so when the loop is appended to the loop run doesn't extend

Here

v = [1, 1]
for i in range(len(v)):
    v.append(1)
    print(v)

You iterate a list that contains [0 1]. That list is contructed by using the length of v but is otherwise unrelated to v.

Here

v = [1, 1]
for i in v:
    v.append(1)
    print(v)

You iterate elements of v. As you append elements to v inside the loop you never reach the end.

Concerning C++ and R: they are different languages, so it should not be a big surprise that code that looks similar syntax-wise does something different.

v = [1, 1]
for i in v:
    v.append(1)
    print(v)

When you do the above code - it means , you are looping through an array/list - v - & inside the loop going on adding elements to it - it will never end.

When you do the code with len(v) - len(v) will be evaluated and assigned as fixed number of times to iterate.

However, ideally one shouldn't be messing up with the variable used for defining number of iterations of loop inside the same loop.

This happened because in every iteration of your for loop, you're updating your vector v. Then when it's run again It will read a vector bigger then the last iteration which will results in and endless loop, for instance:

 v = [1, 1]
 for i in v:
    v.append(1)
    print(v) ## By this point you have v = [1,1,1], then let`s start the loop again
 # v = [1, 1, 1]
 for i in v: # v now has the len(v) = 3, not 2. And it keeps getting bigger and bigger, resulting in an infinite loop.
    v.append(1)
    print(v) # now v = [1,1,1,1]

The best approach is to set a limit to your iteration using range.

Related