+ 2
Why is this different?
Scenario 1 y = [1, 2, 3] for x in y: y = y + [x] #note this line print(y) Output: [1, 2, 3, 1][1, 2, 3, 1, 2][1, 2, 3, 1, 2, 3] Scenario 2 y = [1, 2, 3] for x in y: y += [x] #note this line print(y) Outputs: [1, 2, 3, 1][1, 2, 3, 1, 2][1, 2, 3, 1, 2, 3][1, 2, 3, 1, 2, 3, 1] .... so on, to infinity
4 Answers
+ 8
y = [ 1, 2, 3 ]
print( id( y ), '<-- Original list' )
for x in y:
y = y + [ x ]
print( id( y ) )
# Here a new `list` object named <y> is created in each loop iteration. Thus the original `list` <y> remains intact.
print()
y = [ 1, 2, 3 ]
print( id( y ), '<-- Original list' )
for x in y:
y += [ x ]
print( id( y ) )
# Here original `list` <y> is updated by adding new element in each loop iteration.
Because we're adding new items, each update makes the `for...in` loop extends the loop range (due to <y> growing longer), and this in turn, turn it a close-to-infinite loop which will *probably* stop only when the system runs out of memory to allocate for <y> growth.
+ 6
I think the difference is between __add__ and __iadd__ magic methods of list.
__iadd__ (means in-place add) mutates current list, and __add__ returns new list.
In scenario 2, the expression of y += [x] calls __iadd__ and therefore y list updates every time.
+ 1
Both will give the same output their is no difference
+= Is same as
= +
(a+=b ) == (a+b) //
+ 1
+ is an arithmetic operator
+= is an assignment operator