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?
+=
operates in-place, whereas+
tries to create a new object. – Mulberrya += map(abs, a)
causing an infinite loop is a very interesting example! – Sgraffito