deleteing item from a copy of a list

Discussion in 'Python' started by timmy, Nov 14, 2006.

  1. timmy

    timmy Guest

    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
     
    timmy, Nov 14, 2006
    #1
    1. Advertisements

  2. you're not removing something from Roster2, you're removing something
    from the last item in Roster2. the append methods adds a reference to
    an object to a list; it doesn't copy the object.

    </F>
     
    Fredrik Lundh, Nov 14, 2006
    #2
    1. Advertisements

  3. timmy

    Peter Otten Guest

    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):
    .... ["Tim", "12345", "some more"],
    .... ["Jack", "54321", "whatever"],
    .... ]
    .... item = list(item)
    .... del item[1]
    .... roster2.append(item)
    ....
    [['Tim', 'some more'], ['Jack', 'whatever']]

    Peter
     
    Peter Otten, Nov 14, 2006
    #3
  4. 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
     
    Mikael Olofsson, Nov 14, 2006
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.