To justify this behavior it will be necessary to comment on mutable and immutable objects. In short, mutable objects allow their value to be changed, while immutable.
Its object b
is the type int
, which is immutable and therefore does not allow to have its value changed. But how can I do b += 1
then and increase its value? What actually happens is the creation of a new object of the type int
with the value b+1
and the envelope of b
original by the new object.
So why doesn’t it work in one case and not in another?
When you pass the object to the function, all this operation will occur on the object bb
, which is the function parameter, existing only locally. When you do print(b)
, you will still be displaying the original object, no changes, so zero appears.
When you directly modify this object in the global scope, as you did in the loop for
, you lose the original object reference b
and will always have an "updated version" and, therefore, is displayed the value 6.
As commented, the simplest solution is you make the due counter return in function:
def how_many_integers(aa):
bb = 0
for i in aa:
if isinstance(i, int):
bb += 1
return bb
b = how_many_integers(a)
print(b) # 6
Because you can’t pass an integer in Python by reference. So when you change
bb
within the function, the variableb
passed as argument continues to store the value 0. A possible solution would be to declare b as a list, typeb = [0]
and within the function usebb[0] += 1
, It would work, but the architecture would still suck. I mean, if a function counts the number of integers, that amount has to be its return value and not the change of one of its arguments.– Vander Santos
The variable
bb
is a function parameter, and any modification made there does not change theb
that is out of function - see here a more detailed explanation. No function works because you are changing the variable itselfb
. The simplest is to make the function return the counterbb
: https://ideone.com/zgsbwS– hkotsubo
Thanks guys, it helped a lot!
– Bruno R