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?