JuanPablo
JuanPablo

Reputation: 24774

Make it so when I remove an element from one list, it's removed from another

How I can have the same element in two different lists, such that if I remove it from one list, it's also removed from the other?

a = [..., element, ...]
b = [..., element, ...]

a.remove(element)
element in b # False

Upvotes: 2

Views: 144

Answers (3)

Ray
Ray

Reputation: 1667

In pygame, the sprite class has a kill method. When called, all spriteGroups containing the sprite will remove it from them. So if your element is not as simple as int, you may use this pattern.

Upvotes: 0

Senthil Kumaran
Senthil Kumaran

Reputation: 56901

If you use element as a list, then you can stand a chance of affecting both items in a and b, when you do some operations on the list element.

>>> element = [10]
>>> a = [1,element,2]
>>> b = [3,element,4]
>>> a
[1, [10], 2]
>>> b
[3, [10], 4]

>>> element.pop(0)
10
>>> a
[1, [], 2]
>>> b
[3, [], 4]
>>> filter(None,a)
[1, 2]
>>> filter(None,b)
[3, 4]

You have to careful while doing this, because you are playing with the same instance. If you assign something else, like

element = 10

Then you are creating a new object by name element and it is no longer the one which is referenced in the list. I find the other answer by Niklas. B, quite an interesting as well, where you are just abstracting your requirements into a class.

Upvotes: 1

David Wolever
David Wolever

Reputation: 154534

In short, you can't.

In longer, to do this, you would either need to make the two lists identical, or write a wrapper around the list class which can take care of the removal, then make sure that both lists are an instance of that class.

Upvotes: 1

Related Questions