Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Can += in Python be used as an accumulator?
I'm taking a Python course and not sure how to use these kinds of operators.
1 Answer
- husoskiLv 73 months ago
If you're thinking about numeric data, then the answer is, "Not quite, but it's close enough that if you want to think of it that way then you're not far wrong."
Python numbers are "immutable" objects. This applies to int, float, and complex built-in types. Once an immutable object is created, it can't be changed. When you execute the statement:
count = 1
...Python creates an int object with the value 1, and binds the name "count" to refer to that object. That's sort of like loading a value into an accumulator. If you then execute the statement:
count += 5
...Python does NOT change the 1 object by adding 5 to it. An int object is immutable and can't change. Instead, Python converts that to:
count = count + 5
Then Python...
(1) creates a temporary int object with the value 5;
(2) calls the + operator to add the values of the 1 object that count points to
and the 5 just created; which
(3) produces a new int object with the value 1+5 = 6; and finally
(4) rebinds the name "count" to refer to that object.
A true accumulator is a mutable object; one that you can change the value contained in that accumulator. However, the above sequence starts with the variable "count" referring to the value 1 and ends with it referring to the value 1+5=6, so that's as close as Python can come to having a true accumulator using built-in numeric types.