Roudy Tarabay
Roudy Tarabay

Reputation: 449

python-How to delete an object in a list based on its data member

So i made the class below and stored instances of it in a list.

class Word:
    def __init__(self,word,definition,synonyms):
        self.w=word
        self.defi=definition
        self.synonyms=synonyms

I'm sure i can loop through the list and check every instance but i'm trying to do so using the remove method of a list. x is a list of Word objects

word="hi"
x.remove(Word if Word.w==word)

this gave me an error. So is there a similar way to do it?

EDIT I was trying to simplify my question but apparently my intentions weren't clear. I have a dictionary whose keys are the 2 last letters of words (that users add) and whose values are lists of the words with those 2 last characters. Example:

w1=Word("lengthen","make something taller","some synonym")
w2=Word("woken","let someone wake up","some synonym")
w3=Word("fax","machine used for communication","some synonym")
w4=Word("wax","chemical substance","some synonym")
 ['en':(w1,w2),'ax':(w3,w4)] 

I am trying to define a method delete which take the dictionary and a word(STRING), then it will delete the OBJECT Word containing the following word.

def delete(dictionary,word):
    if word[-2:] in dictionary:
        x=dictionary[word[-2:]]
        if(x.count(word)!=0):
            x.remove(Word if Word.w==word)

Upvotes: 0

Views: 110

Answers (2)

martineau
martineau

Reputation: 123521

I think this will do what you want:

class Word:
    def __init__(self,word,definition,synonyms):
        self.w=word
        self.defi=definition
        self.synonyms=synonyms
    def __repr__(self):  # added to facilitate printing of tuples of Word objects
        return 'Word({}, {}, {})'.format(self.w, self.defi, self.synonyms)

w1=Word("lengthen", "make something taller", "some synonym")
w2=Word("woken", "let someone wake up", "some synonym")
w3=Word("fax", "machine used for communication", "some synonym")
w4=Word("wax", "chemical substance", "some synonym")

dictionary = {'en': (w1, w2), 'ax': (w3, w4)}

def delete(dictionary, word):
    suffix = word[-2:]
    if suffix in dictionary:
        dictionary[suffix] = tuple(word_obj for word_obj in dictionary[suffix]
                                   if word_obj.w != word)

delete(dictionary, 'woken')
print(dictionary)

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122126

You would generally use a list comprehension to build a new list without matches, otherwise you end up trying to modify a list while iterating over it:

x = [word for word in x if word.w != "hi"]

Note lowercase word; using Word shadows the class itself.

If altering the list in-place is crucial, you can use slicing:

x[:] = [word for word in x if word.w != "hi"]

Upvotes: 3

Related Questions