Differencebetween I = I + 1 and I += 1 in a 'For' Loop

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.


Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

  • If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

  • If __iadd__ returns NotImplemented, Python falls back to x = x + y.

  • The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.

As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.

You can read more on this in the Python documentation of "Emulating Numeric Types".

These [__i*__] methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. In certain situations, augmented assignment can result in unexpected errors (see Why does a_tuple[i] += ["item"] raise an exception when the addition works?), but this behavior is in fact part of the data model.

What's the difference between i++ vs i=i+1 in an if statement?

If you use i++, the old value will be used for the calculation and the value of i will be increased by 1 afterwards.

For i = i + 1, the opposite is the case: It will first be incremented and only then the calculation will take place.

If you want to have the behavior of the second case with the brevity of the first, use ++i: In this case, i will first be incremented before calculating.

For more details and a more technical explanation, have a look at the docs for Assignment, Arithmetic, and Unary Operators!

Is there a difference between a for loop without increment vs. one with a non incremented variable?

Under normal circumstances: no, there is no difference.

The for statement creates a loop that consists of three optional
expressions, enclosed in parentheses and separated by semicolons,
followed by a statement (usually a block statement) to be
executed in the loop.

The three expressions (initialization, condition and final-expression) are all optional (unlike the semicolons themselves), so if you omit the final-expression (which is most commonly used to increment the i/index/counter) that part simply will not be used.

If you use an isolated i as the final-expression, then this will be evaluated after every iteration of the for-loop. But an isolated variable on its own usually doesn't have any side effects. The value wont change and the value that is returned by the i expression (the value of i) is ignored in case of the final-expression.

console.log('For loop without final-expression:');
for (let i = 0; i < 10;) {
console.log(i++);
}

console.log('For loop with final-expression:');
for (let i = 0; i < 10; i) {
console.log(i++);
}

Is there a difference between ++i and i++ in this loop?

The only difference between i++, ++i, and i += 1 is the value that's returned from the expression. Consider the following:

// Case 1:
var i = 0, r = i++;
console.log(i, r); // 1, 0

// Case 2:
var i = 0, r = ++i;
console.log(i, r); // 1, 1

// Case 3:
var i = 0, r = (i += 1);
console.log(i, r); // 1, 1

In these cases, i remains the same after the increment, but r is different, i += 1 just being a slightly more verbose form of ++i.

In your code, you're not using the return value at all, so no, there is no difference. Personally, I prefer to use i++ unless there is a specific need to use one of the other forms.

What is the difference between ++i and i++?

  • ++i will increment the value of i, and then return the incremented value.

     i = 1;
    j = ++i;
    (i is 2, j is 2)
  • i++ will increment the value of i, but return the original value that i held before being incremented.

     i = 1;
    j = i++;
    (i is 2, j is 1)

For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R.

In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.

The efficiency question is interesting... here's my attempt at an answer:
Is there a performance difference between i++ and ++i in C?

As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.

What's the difference between --i and i--?

If, for example, i = 5:

--i decrements i by 1 then gives you the value of i (4).

i-- gives you the value of i (5) then decrements it by 1.

Both will give you the same result in a for loop.

What is different between two codes of for loop?

There is no difference in the output for the code you wrote. However, if you tried to change the value of x when in the loop, there would be a difference.

#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto x : a)
x = 0;
for (auto x : a)
cout << x << endl;
}

is very different to:

#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto & x : a)
x = 0;

for (auto x : a)
cout << x << endl;
}

In the second, the vector a will be all zeros at the end of the program. This is because auto by itself copies each element to a temporary value inside the loop, whereas auto & takes a reference to an element of the vector, which means that if you assign something to the reference it overwrites wherever the reference is pointing.

Difference between 'for a[-1] in a' and 'for a in a' in Python?

Quoting the official documentation on for loop,

An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices.

So, when you are iterating an object, an iterator object is created and that is used for iteration. That is why the original object is not lost, at least till the loop runs.

In your case, when for a in a: is executed, an iterator object is created for a first, and the values are retrieved from the iterator object. Even though the loop binds the name a to some other value on each iteration, the iterator object still holds reference to the original list object and it gives out values from it. That is why you are not getting any error.



Related Topics



Leave a reply



Submit