Home > Software engineering >  Delete an object in list by ID from another list
Delete an object in list by ID from another list

Time:09-29

How do I delete an object in list by ID from another list?

I have two lists: The first one is a normal list:

ID_list = [45, 56, 78, 11]

Second list is a list which has objects in it. For instance:

Obj_list = [Node.node at x1, Node.node at x2]

And I would like to remove an object by attribute called ID.

Constructor looks like this

class Object:
    def __init__(self, ID=None):
        self.ID = ID

So I want to delete an object from Obj_list which matches with ID number from ID_list.

For instance Node.node at x1 has ID: 45, Node.node at x2 has ID: 46. After deleting... Obj_list would have look like this = [Node.node at x2]

How do I do that?

Thank you for any suggestions.

CodePudding user response:

I would suggest storing your IDs in a set instead of a list for membership testing speed up if you have large amount of IDs. Then you can use a list comprehension or a generator expression.

class Object:
    def __init__(self, ID=None):
        self.ID = ID
    def __repr__(self) -> str:
        return f"Object(ID={self.ID})"


ID_list = {45, 56, 78, 11}
Obj_list = [Object(1), Object(45), Object(2)]
print(Obj_list)
Obj_list[:] = [obj for obj in Obj_list if obj.ID not in ID_list]
print(Obj_list)

output:

[Object(ID=1), Object(ID=45), Object(ID=2)]
[Object(ID=1), Object(ID=2)]

Obj_list[:] does the job in-place(slice assignment). It mutates your list.

CodePudding user response:

In case you dont want to override the list objects, below is code. you need to convert your id list into a set so that unique element id will be there and we can search for ID in O(1) time frame.

Below is code

class Object:
    def __init__(self, ID=None):
        self.id = ID
    def __repr__(self):
        return f"<Object({self.id})>"

ID_list = [45, 56, 78, 11]
unique_ids = set(ID_list)

objects = [Object(1), Object(45), Object(2)]
index = 0
length = len(objects)

while index < length:
    id_ = objects[index].id
    if id_ in unique_ids:
        del objects[index]
        length -=1
    else:
        index =1

CodePudding user response:

I think the other answers are good given the constraints of using 2 lists. However, I think the ideal solution would be to store Obj_list as a dict with the ID as the key. Then you can just del obj_dict[id]

  • Related