Let a = [-1, -2, -3]. I want to modify the list a so that a == [-1, -2, -3, 1, 2, 3], and I want to use map to achieve that.
I have the following different pieces of code I've written to do this:
a = a + map(abs, a)a = a + list(map(abs, a))a += map(abs, a)a += list(map(abs, a))
Here's the results:
TypeError: can only concatenate list (not "map") to list- Works as expected:
a = [-1, -2, -3, 1, 2, 3] - Hangs indefinitely before getting terminated with no error message (potentially ran out of memory?)
- Works as expected:
a = [-1, -2, -3, 1, 2, 3]
I thought that a += b was just syntactic sugar for a = a + b, but, given how (1) and (3) behave, that's clearly that's not the case.
Why does (1) give an error, while (3) seems to go into an infinite loop, despite one generally just being a syntactic sugar version of the other?
As the examples show,
a += bis not equivalent toa = a + b, and this answer explains why.Under the hood,
a += bcalls__iadd__, which, whenais a list, iterates overb, adding each element ofbtoa. However,a = a + bwill call__add__, on (the 2nd)a, which will try to concatenatebto (the 2nd)aessentially all at once, but the method will detect thatbis not alistand fail.The
a += bcase causes an infinite loop, becausemap, when iterated over, only computes and yields one element at a time. Thus, it will yield back the first number,abs(-1) == 1, which will be appended toasoa == [-1, -2, -3, 1]. Then, after the append, it will be asked to yield back the second number,abs(-2) == 2, soa == [-1, -2, -3, 1, 2]. This continues untila == [-1, -2, -3, 1, 2, 3], and then still continues (because there are now more values inathan just the original three values.). Somapwill returnabs(1) == 1next, and so nowa == [-1, -2, -3, 1, 2, 3, 1]and then on the next step,a == [-1, -2, -3, 1, 2, 3, 1, 2], and so on, until it runs out of memory.In short,
+=calls__iadd__and+calls__add__and they're implemented differently. The__iadd__function will run on anything that can be iterated over, but__add__does a type check to make sure the thing it's concatenating is a list. Thus,+=causes an infinite loop while+leads to an error.