+ 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

5th Jun 2023, 6:42 PM
TheUnknown
TheUnknown - avatar
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.
6th Jun 2023, 2:08 AM
Ipang
+ 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.
5th Jun 2023, 7:33 PM
Artin Azari
Artin Azari - avatar
+ 1
Both will give the same output their is no difference += Is same as = + (a+=b ) == (a+b) //
5th Jun 2023, 7:22 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
+ is an arithmetic operator += is an assignment operator
5th Jun 2023, 7:47 PM
**🇩đŸ‡Ș|🇩đŸ‡Ș**
**🇩đŸ‡Ș|🇩đŸ‡Ș** - avatar