1

I know that [:] doing is shallow copy(member is not copied) ,still can someone explain this behaviour:

>>> a=[['a','b','c','a','b','c','a','b','c'],
...                        ['c','a','b','c','a','b','c','a','b'],
...                        ['b','c','a','b','c','a','b','c','a']
...                        ]
>>> for i in a:
...     i=i[4:]
... 
>>> a
[['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'], ['c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b'], ['b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']]
>>> 

why a is still not changed? Sorry for noob question.

Wumpus
  • 37
  • 7
  • possible duplicate of [Modify values of a list while iterating over it in Python?](http://stackoverflow.com/questions/14406449/modify-values-of-a-list-while-iterating-over-it-in-python) – Karl Knechtel Dec 29 '13 at 16:08

1 Answers1

4

When you say

i=i[4:]

you are not actually altering i to i[4:], you are simply making i point to i[4:]. i is merely a reference to the actual list. In order to really change the data,

i[:]=i[4:]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Nice answer. Before reading this, I thought it has to be `for i in xrange(a): a[i] = a[i][4:]`. – WKPlus Dec 29 '13 at 15:35