1

I'm new to programming and Python. The problem I have is with removing list elements that are instances of custom class.

import copy

class some_class:
    pass

x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5

z = [x,y]
zcopy = copy.deepcopy(z)
z.remove(zcopy[0])

This returns: ValueError: list.remove(x): x not in list

Is there a simple way to remove element from list by using reference from deepcopied list?

edit: Thanks for your answers. I found some solution using indexing. It's not pretty but it does the job:

import copy

class some_class:
    pass

x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5

z = [x,y]
zcopy = copy.deepcopy(z)
del z[zcopy.index(zcopy[0])]
3
  • 2
    You should avoid this kind of copying. There may be simpler ways to partition a list. What are you trying to do? Commented Aug 10, 2010 at 19:35
  • Basically, I use functions that, when applied, modify this list by performing calculations (some kind of monte carlo simulation). So, I want to use functions on a copy of instance and remove answer (which I got from running simulation) from original list so I can run simulation again on modified list. list -> function(copy of list) -> answer -> remove answer from original list -> function(copy of list with removed answer) -> ... Commented Aug 10, 2010 at 19:54
  • 1
    That's not a very good design. You should not be putting the answers into the same list. You need to filter, creating a new list, not update an existing list. And you rarely need to copy anything. You should post more details on this algorithm of yours so that we can help you fix it. Commented Aug 10, 2010 at 20:49

1 Answer 1

1

No, because the call to deepcopy creates a copy of the some_class instance. That copy, zcopy[0] is a different object from the original, z[0], so when you try to remove zcopy[0] from the list z, it rightly complains that the copy doesn't exist in the original list. Furthermore, there is no link between the copied object and the original object, which is the intent of deepcopy.

I suppose you could implement a __deepcopy__ method in your class, which returns a copy that maintains some reference to the original object. Then you could use that reference to get the original object, z[0], from the copy, zcopy[0]. It strikes me as a rather odd thing to do, though, and probably not a good idea. Without further information, I'd suggest just using copy.copy instead of copy.deepcopy.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.