3 ms·
+= on lists is an annoying one: def myfunc(mylist): mylist += [1,2,3] is NOT the same as: def myfunc(mylist): mylist = mylist + [1,2,
by ketralnis 11y ago
+= on lists is an annoying one:
def myfunc(mylist):
mylist += [1,2,3]
is NOT the same as:
def myfunc(mylist):
mylist = mylist + [1,2,3]
Try this on each of those definitions:
a = [4,5,6]
myfunc(a)
print a
The first one mutates 'a', the second only reassigns (and discards) a temporary `mylist`.
Put another way, += is not just syntactic sugar. With lists, it actually mutates the original list.
- pikzen 11y agoWhich is what every language with a C inheritance does. += has always mutated the original value, I don't know why you expected it to be different. To me the real wtf is the second, where python creates a variable with the same name and discards it.
- chei0aiV 11y agoWhich is what every language with a C inheritance does. Arguments are passed by value and put into ordinary variables, I don't know why you expected it to be different.
- ketralnis 11y agoWell no. What would you expect this code to do? void increment(int x) { x += 1; } void printit() { int y = 0; increment(y); printf("%d\n", y); } C doesn't have lists so I had to use an int here, but the Python example does the equivalent of that code printing 1, not 0. (But only for lists. That same Python code with ints does what you expect.)
- albertzeyer 11y agoIt is syntactic sugar to call mylist.__iadd__. The behavior to modify it inplace is common also for other non-pure data structures. I'm not sure but I think that list.__iadd__ is even more tricky: When the new object still fits into the allocated array, it will modify it inplace, otherwise it returns a newly allocated list and doesn't modify it inplace. So you cannot rely on __iadd__ modifying a list (or anything else) inplace.
- Veedrac 11y ago> I'm not sure but I think that list.__iadd__ is even more tricky False; __iadd__ is always in-place for lists.