0

Im not sure why my code does not do what I want (I want to return a list of unique items)

B = ["blue", "blue", "red",   "green", "red",  "blue", "yellow", "green", "blue", "red"]
def makeUnique(list):
    unique = []
    for i in range(0, len(list)):
        if list[i] not in unique:
            unique.append(item)
    return unique
print makeUnique(B)

It returns

['red', 'red', 'red', 'red', 'red', 'red', 'red']

Edit: idents might be incorrect, when pasting some was missing, so its not a ident error or sth

Jozef Plata
  • 350
  • 4
  • 11
  • Try: `unique.append(list[i])` – Maurice Meyer Jun 21 '17 at 17:29
  • Omg thank you :) I think Im tired... – Jozef Plata Jun 21 '17 at 17:34
  • Searching other questions already answered is often the best way to find an effective, tested solution. One line command: https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python – Douglas Jun 21 '17 at 17:35
  • Or change your loop to `for item in list:` and use `item` rather that `list[i]`. On a side note, it's bad practice to use builtins as variable names. – zondo Jun 21 '17 at 17:35

2 Answers2

3

Maurice Meyer already found the bug in your code, but in general, this algorithm is not optimal - to find unique values in a list, just do:

newlist = list(set(oldlist))
Błotosmętek
  • 12,717
  • 19
  • 29
2

You're appending item, which doesn't exist in the context of the function. You have to append the item you're iterating over:

B = ["blue", "blue", "red",   "green", "red",  "blue", "yellow", "green", "blue", "red"]

def makeUnique(list):
    unique = []
    for i in range(0, len(list)):
        if list[i] not in unique:
            unique.append(list[i])
    return unique


print(makeUnique(B))  # ['blue', 'red', 'green', 'yellow']