deleteing item from a copy of a list

Mikael Olofsson mikael at isy.liu.se
Tue Nov 14 10:37:42 CET 2006


timmy 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
>   

First of all, you could have said

    del Roster2[-1][1]

since negative indices count backwards from the end of the list. This 
has nothing to do with your problem, though.

Fredrik has already given you a correct, somewhat condensed, answer. Let 
me elaborate. I guess that Roster is a list of lists. Then actually, it 
is a list of references to lists (really a reference to a list of 
references to lists). Your for-loop makes Roster2 a shallow copy of 
Roster, i.e. Roster2 is a new list with references to the _same_ 
sublists as in Roster. So, Roster2[-1] references the same object as 
Roster[-1], not a copy of it. To get copies, you could change your 
.append-line to

    Roster2.append(ShiftLine[:])

which gives you shallow copies of the sublists. If there are mutables in 
the sublists, you may still get into trouble. In that case, maybe you 
should take a look at copy.deepcopy.

HTH
/MiO



More information about the Python-list mailing list