-5

Hi I am new to R and Python, just trying to understand why the below code is not giving infinite value:

in R :
for (i in 1:10) {
  print(i)
  i=5
}

Result:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

in Python:

for i in range(10):
    print(i)
    i = 5 

Result:

0
1
2
3
4
5
6
7
8
9

As we are setting the value after each iteration of i to 5, it should go into infinite loop. Please help me to understand.

Thanks in advance. Ashish

  • 2
    Because it gets reset at the top of the loop by the for statement. – Mike Wise Sep 08 '17 at 05:13
  • 4
    You may be resetting `i` to `5` but immediately after the `for` loop resets `i` to the next value in the range. – Julien Sep 08 '17 at 05:13
  • Firstly that would be the worst way to make an infinite loop, Secondly, for loop doesn't work that way! @Julien , Pretty much gave the explanation! – Ubdus Samad Sep 08 '17 at 05:16
  • even stackoverflow doesn't work like this, you are asking to make infinite for loop in R and python both at a time and not specifying why you need infinite loop. just a simple comment is possible her. use `while` loop without breaking condition, it will work – Gahan Sep 08 '17 at 05:18
  • @Gahan, I am just trying to understanding , how the loop works. – ashish chandan Sep 08 '17 at 05:24
  • then check this : https://stackoverflow.com/documentation/python/237/loops and your question is similar to : https://stackoverflow.com/questions/15363138/scope-of-python-variable-in-for-loop – Gahan Sep 08 '17 at 05:40
  • You can use a while loop to make an infinite loop in R. i = 1; while(i < Inf) { print(i) i = i + 1 } To break out of the loop press Esc. I find it pretty cool that R has concept of infinity. – xyz123 Sep 08 '17 at 06:02

1 Answers1

0

Legit question and unfair downvotes!

In R, i in for loops behaves as if it is stored, incremented and reloaded at each iteration from another environment (and maybe it is), it's not like this in all languages, but it's this way in R.

from R Inferno :

8.1.64 iterate is sacrosanct

In the following loop there are two uses of 'i'.

> for(i in 1:3) f
+ cat("i is", i, "nn")
+ i <- rpois(1, lambda=100)
+ cat("end iteration", i, "nn")
+ g

i is 1
end iteration 93
i is 2
end iteration 91
i is 3
end iteration 101

The i that is created in the body of the loop is used during that iteration but does not change the i that starts the next iteration. This is unlike a number of other languages (including S+).

This is proof that R is hard to confuse, but such code will denitely confuse humans. So avoid it.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167