I'm a newcomer to Python but I understand that things should not be done this way, so please consider the following code snippets as purely educational :-)
I'm currently reading 'Learning Python' and trying to fully understand the following example:
>>> L = [1, 2, 3, 4, 5] >>> for x in L: ... x += 1 ... >>> L [1, 2, 3, 4, 5] I did not understand if this behavior was somewhat related to the immutability of the numeric types, so I've run the following test:
>>> L = [[1], [2], [3], [4], [5]] >>> for x in L: ... x += ['_'] ... >>> L [[1, '_'], [2, '_'], [3, '_'], [4, '_'], [5, '_']] Question: what makes the list unchanged in the first code and changed in the second ?
My intuition is that the syntax is misleading and that:
x += 1for an integer really meansx = x + 1(thus assigning a new reference)x += ['_']for a list really meansx.extend('_')(thus changing the list in place)
[x+1 for x in L]L = [x+1 for x in L]if you don't want a new list, then :)Lto refer to the new list.