user1817188
user1817188

Reputation: 517

Remove element in a list with condition

I have a class named Info where Info has a string type instance variable which can be accessed by Info.getName()

Also I have a list of instance Info such as class_list = [Info('Aleck'), Info('John')].

Given a name_list = ['Aleck', 'Bob'], I would like to remove the element in class_list with the same name in name_list, while i also need to know if a name (such as Bob) is not in class_list (for example print out that bob is not in list)

for above example the result should be class_list = [Info('John')] and print out that bob is not on the list.

I know ugly way of doing so such as the following codes (i am not actually running it, just an example), is there elegant or Pythonic way to do this?

def removeElement(name_list, class_list):
    list_to_be_removed = []
    for name in name_list:
        is_name_in_list = false
        for obj in class_list
            if name == obj.getName():
                list_to_be_removed.add(obj)
                is_name_in_list = true
                break
        if is_name_in_list == false:
            print name + ' is not in the list'
        is_name_in_list = false

    for obj in list_to_be_removed:
        class_list.remove(obj)

Upvotes: 2

Views: 5459

Answers (2)

Kugel
Kugel

Reputation: 19814

You don't have classes, you have class instances. Info('Alice') is a constructor call, that creates an instance of your Info class.

How about this:

filtered = [info for info in info_list if info.get_name() not in name_list]

Alternatively:

filtered = filter(lambda o: o not in name_list, info_list)

If you have a lot of names convert your name_list into a set and use that.

name_set = set(name_list)

Upvotes: 5

Mr Fooz
Mr Fooz

Reputation: 111856

List comprehensions are your friend.

def remove_names(names_to_remove, info_list):
    return [info
            for info in info_list
            if info.getName() not in names_to_remove]

I changed the names of most variables to be closer to what I think you mean.

Upvotes: 4

Related Questions