1

I am attempting to make a function that will return the unique numbers of a list, in list form. For example:

l = [1,2,2,3,4]

My function would return: [1,2,3,4]

I used a set to do this, and my code is as follows:

def unique_list(l):
    se = set(l)
    lis = [se]
    return lis
print(unique_list(t))

And my output is: [set([1, 2, 3, 4, 5, 6, 7, 8])]

I would assume it has something to do with the se = set(l) or lis = [se] part of my code. However, I am learning by myself and am not exactly sure what could be causing this.

mkamin15
  • 37
  • 4
  • 2
    `def unique_list(l): return list(set(l))`. `[..]` does not create a list from the set's elements, it only encloses the the set object as a single element in a list (not the same thing). – cs95 Jan 10 '18 at 03:29
  • Okay, so instead of saying `se = set(l)` I can just directly create a list by doing `return list(set(l))` ? Thanks, I never knew that! – mkamin15 Jan 10 '18 at 03:32

3 Answers3

1

You are casting the list incorrectly. Try something like this..

def unique_list(l):
    se = set(l)
    lis = list(se)
    return lis
print(unique_list(t))
Jake
  • 617
  • 1
  • 6
  • 21
  • I would even skip the `se = set(l)` and just do `lis = list(set(l))` – r.ook Jan 10 '18 at 04:02
  • There is little need to use a function at all, could just use `list(set(l))` in line. However that isn't very helpful to explain why the code didn't work properly. – Jake Jan 10 '18 at 04:05
  • Well, it's good to know that but my 'assignment' from this video series was to make a function that does it for me. – mkamin15 Jan 10 '18 at 22:31
1
l = [5,5,1,2,2,3,4]

def unique_list(l):
    se = set(l)  # get all the unique elements of list
    lis = list(se)  # convert set to list
    lis.sort(key=l.index)  # preserve order of original list
    return lis
print(unique_list(l))
Gahan
  • 4,075
  • 4
  • 24
  • 44
0

list(set(list_)) is fast for returning a list of unordered unique items.

set(list_) is sufficient for a unique collection if a list not critical.

Here are ways to remove replicates from a list_ while preserving order:

import collections as ct


list(ct.OrderedDict.fromkeys(list_))

In Python 3.6+:

list(dict.fromkeys(list_))

See also this SO post by R. Hettinger and this blog on Fastest way to uniquify a list in Python >=3.6

pylang
  • 40,867
  • 14
  • 129
  • 121