deleteing item from a copy of a list

Peter Otten __peter__ at web.de
Tue Nov 14 10:21:32 CET 2006


timmy <"timothy at open-networks.net"> wrote:

> i make a copy of a list, and delete an item from it and it deletes it 
> from the orginal as well, what the hell is going on?!?!?!
> 
> #create the staff copy of the roster
>         Roster2 = []
>         for ShiftLine in Roster:
>                 #delete phone number from staff copy
>                 Roster2.append(ShiftLine)
>                 del Roster2[len(Roster2)-1][1]
> 
> Roster2 should have nothing to do with Roster, right??? doing a print of 
> both lists confirms that the phone number has been removed from both

You seem to have a list of lists and are making a new outer list. The lists
inside that outer list are not copied. You can copy them by calling
list(item) or copy.copy(item):

>>> roster = [
...     ["Tim", "12345", "some more"],
...     ["Jack", "54321", "whatever"],
... ]
>>> roster2 = []
>>> for item in roster:
...     item = list(item)
...     del item[1]
...     roster2.append(item)
...
>>> roster
[['Tim', '12345', 'some more'], ['Jack', '54321', 'whatever']]
>>> roster2
[['Tim', 'some more'], ['Jack', 'whatever']]

Peter



More information about the Python-list mailing list