1

I am working my way through the Think Python Textbook, and one of the problems it gives is to make a function that takes a list and returns a list with only unique elements from the original. What I have so far is this:

def remove_duplicates(l):
    index = 0
    new_l = []
    dup_l = []
    while index < len(l):
        if l[index] in l[index+1:] or l[index] in new_l:
            dup_l += [l[index]]
            index = index + 1
        elif l[index] in dup_l:
            index = index + 1
        else:
            new_l += [l[index]]
    return new_l

I feel like there must be a more succinct, pythonic way to write this function. Can somebody help this beginner programmer?

  • I duped you to the canonical post about returning a list with only unique elements that *preserves order*. If order doesn't matter, just use `return list(set(l))`. – Martijn Pieters Jun 11 '16 at 22:46
  • I disagree with the duplicate because Jeremy seems to be asking of a way to do it manually, so I've added that answer. Marking as duplicate like may come up as not very new user friendly, – Juan Cortés Jun 11 '16 at 22:56
  • Thanks guys very much! – Jeremy Odell Jun 12 '16 at 17:01

1 Answers1

2

I assume you want to do it manually, to understand python syntax so this is a way of doing it.

Update for the comment made about only getting elements that occur only once and not removing duplicates, you can replace the if condition to if L.count(element) == 1: and it will return [1,2,4] as you were requesting.

def unique(L):
    uniqueElements = []
    for element in L:
        if element not in uniqueElements:
            uniqueElements.append(element)
    return uniqueElements

print(unique([1,2,3,3,4]))

And if you want to delve further into the python syntax, you could do a list comprehension and simplify it further, while still not using the set method which loses the order of elements:

def unique(L): return [element for element in L if L.count(element) == 1] 
Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
  • Well, actually the problem I was trying to solve would make a list that would have returned `print(unique([1,2,3,3,4])) ---> [1, 2, 4]` This is because I want only unique elements from the input list, not just a list that deletes duplicates. Also how is my comment formatting? – Jeremy Odell Jun 12 '16 at 17:03
  • Replace the `if` condition to `if L.count(element) == 1:` do get `[1,2,4]` – Juan Cortés Jun 12 '16 at 17:27