So-hyeon Jung
So-hyeon Jung

Reputation: 21

How to remove duplicates from a list in only one method?

I want to remove duplicates in the list, but append elements in the list when there are no duplicates in the existing data but only in the extend() method, not in the append() method (because I will treat an added list in the append() method as one distinctive datum).

from collections import UserList

class Ulist(UserList):
    def __init__(self, list_=[]):
         UserList.__init__(self)
         self.list_=list_

    def __add__(self, another):
        for i in another:
            if i in self:
                raise ValueError
                print("Duplicated Data!")
            else:
                return UserList.__add__(self, another)

    def append(self, another):
        if another in self:
            raise ValueError
            print("Duplicated Data!")
        else:
            return UserList.append(self, another)

    def extend(self, another):
        for x in another:
            if x in self:
                print("Duplicated Data! Erase the Duplicated Data")
                listList=UserList.extend(self, another)
                listList=list(set(listList))
                return listList
                       
            else:
                return UserList.extend(self, another)

And this is the error message when I work with the list having an element duplicated with the existing list. I don't understand how TypeError: 'NoneType' object is not iterable applies. How do I correct the extend() method?

>>> l=Ulist()
>>> l.__add__([98])
[]
>>> l.append('kim')
>>> l.extend(['lee', 'park', 'choi'])
>>> l.append(['kim', 'jeong', 'kang'])
>>> l.extend(['lee', 'kim', 'joo'])
Duplicated Data! Erase the Duplicated Data
Traceback (most recent call last):
  File "<pyshell#110>", line 1, in <module>
    l.extend(['lee', 'kim', 'joo'])
  File "C:\Users\소현\AppData\Local\Programs\Python\Python38-32\User_list.py", line 28, in extend
    listList=list(set(listList))
TypeError: 'NoneType' object is not iterable

Upvotes: 1

Views: 145

Answers (5)

alani
alani

Reputation: 13079

Various issues with the code:

  • self.list_ is never used (and the base class does not use it either), so just remove it. Having removed it, there is no further purpose for your __init__, so remove that also. (If you did use it, then using a mutable argument as function default would also be a problem.)

  • UserList.append and UserList.extend both return None so there is no point in explicitly returning this value in your overridden versions (it will default to returning None on reaching end of the function).

  • You have statements after raise statements, which cannot be reached. Get rid of them, and you can incorporate the messages into the exception message.

  • In your extend, you are trying to iterate over the None returned from UserList.extend, and even if the item is not already found, you have a problem that you are doing the extend inside a loop over items so you can end up with the whole another list added multiple times.

  • It would also be a good idea to use super so that instead of Userlist.append(self, another) you use super().append(another). This would make it easier later to change which base class you inherit from.

Here is a revised version:

from collections import UserList

class Ulist(UserList):

    def __add__(self, another):
        for i in another:
            if i in self:
                raise ValueError("Duplicated Data!")
            else:
                return super().__add__(another)

    def append(self, another):
        if another in self:
            raise ValueError("Duplicated Data!")
        else:
            super().append(another)

    def extend(self, another):
        for x in another:
            if x in self:
                print("Duplicated Data! Erase the Duplicated Data")
            else:
                super().append(x)

Or you could also change extend to utilise the append method shown here:

    def extend(self, another):
        for x in another:
            try:
                self.append(x)
            except ValueError as exc:
                print(exc)

Upvotes: 1

Nadavo
Nadavo

Reputation: 250

the problematic line is this one:

                listList=UserList.extend(self, another)

here it seems to me that maybe the Userlist object is not initiated properly, and thus is None type. it is hard to tell what to do because we don't have the UserList init() method, but I think you might heave meant to do somthing such as:

def extend(self, another):
        for x in another:
            if x in self:
                print("Duplicated Data! Erase the Duplicated Data")
                listList=UserList(   ----- put args here ----     ).extend(self, another)
                listList=list(set(listList))
                return listList

Upvotes: 0

Vinayak Mikkal
Vinayak Mikkal

Reputation: 87

After adding all the elements you want then use the following

x = list(set(x))

This will remove all the duplicates.

Upvotes: -1

Jan Str&#225;nsk&#253;
Jan Str&#225;nsk&#253;

Reputation: 1691

The problem here is that UserList.extend returns nothing (None). So in your code

                listList=UserList.extend(self, another)
                listList=list(set(listList))

listList on the first line is None. Then when you pass it to set, you get this error (the same as set(None))

Upvotes: 4

monkut
monkut

Reputation: 43860

Sounds like you're looking for set().

items = (
    "kim",
    "lee",
    "park",
    "choi",
    "kim",
    "jeong",
    "kang",
    "lee",
    "kim",
    "joo"
)
uniques = set()
for item in items:
    uniques.add(item)

This will only keep the unique items you add to the set.

Results:

{'choi', 'jeong', 'joo', 'kang', 'kim', 'lee', 'park'}

Upvotes: 0

Related Questions