Python Warts

misfeatures and other problems
PERL| PHP| PYTHON| RUBY
Answers: (all questions)
(question)
Question:
#!/usr/bin/python

a = [1,2,3]
b = a

a += [4]
b = b + [5]

print "a=%s" % a
print "b=%s" % b
Answer:
Output:
a=[1, 2, 3, 4]
b=[1, 2, 3, 4, 5]
The += operator does not do the same thing as writing foo = foo + value.

For non-mutable objects, the effect is almost always the same, but mutable objects behave differently. The += operator is designed to change an object in-place, where the longer method will produce a new object and re-bind the name to the new object. Taking away the syntactic sugar, the example could be written more explicitly as:
a = [1,2,3]
b = a

a.__iadd__([4])
b = b.__add__([5])
PERL| PHP| PYTHON| RUBY
Last modified: March 30, 2006 @ 7:04 MST
Copyright (C) 1996-2024 Selene ToyKeeper