Why Do List Operations In Python Operate Outside Of The Function Scope?
Solution 1:
The short answer is because lists are mutable and integers are immutable.
You cannot mutate an integer in place, so we call it 'immutable'. With this in mind, things like addition on an integer do not modify the original object, but rather return a new value- so your original variable will remain the same. Therefore, if we store a reference to an integer, they will only be the same object as long as we have not changed either one of them:
>>> foo = 1
>>> bar = foo
>>> foo is bar
True
>>> foo += 2
3
>>> foo
3
>>> bar
1
>>> foo is bar
False
On the other hand lists are 'mutable' (can modify that same object reference), and operations like pop()
mutate the list
in-place, changing the original. This also means that if you edit a reference to a mutable object such as a list
, the original will be changed as well:
>>> baz = [1, 2, 3, 4, 5]
>>> qux = baz
>>> qux is baz
True
>>> baz.pop()
5
>>> qux
[1, 2, 3, 4]
>>> baz
[1, 2, 3, 4]
>>> qux is baz
True
Solution 2:
Passing objects to functions works the same way as assigning them. So, what you're seeing is the same effect as this:
>>> words = ["A", "list", "of", "words"]
>>> stuff = words
>>> stuff.pop()
'words'
>>> words
['A', 'list', 'of']
This happens because stuff
and words
are the same list, and pop
changes that list. ints are immutable, meaning they don't support any in-place mutations: every time you change its value, it gives you a different int object with the new value. You can test whether two objects are the same or distinct objects using the is
operator:
>>> stuff is words
True
>>> a = 5
>>> b = a
>>> a is b
True
>>> b += 1
>>> a is b
False
Solution 3:
When you do stuff.pop()
you modify the object stuff
. When you do num = num + 1
you don't modify num
, you just create a new object and assign it to the variable num
. If num
were a list, the result would be exactly the same:
def addone(num):
num = num + [1]
print "function: added 1, now", num
number = [5]
print "Before:", number
addone(number)
print "After:", number
# Before: [5]
# function: added 1, now [5, 1]
# After: [5]
Post a Comment for "Why Do List Operations In Python Operate Outside Of The Function Scope?"