2

The return value of sort() is None so the following code doesn't work:

def sorted_unique_items(a):
   return list(set(a)).sort()

Any idea for better solution?

mko
  • 21,334
  • 49
  • 130
  • 191

4 Answers4

6

Use sorted():

sorted(set(a))

and you can omit the list() call entirely.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Its simple Just use the sorted() method :

data = [10,5,46,4]
sorted_data = sorted(data)
print "Sorted Data ::::",sorted_data
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Anil Kesariya
  • 1,044
  • 1
  • 7
  • 13
0

Above solution is only work for hashable type like string,integer and tuple but it not work for unhashable type like list.

for example if you have a list data= [[2],[1],[2],[4]]

for unhashable type best solution is :

from itertools import izip, islice

values= [[2],[1],[2],[4]]

def sort_unique_unhashable(values):

    values = sorted(values)
    if not values:
        return []
    consecutive_pairs = izip(values, islice(values, 1, len(values)))
    result = [a for (a, b) in consecutive_pairs if a != b]
    result.append(values[-1])
    return result
print sort_unique_unhashable(values)
georg
  • 211,518
  • 52
  • 313
  • 390
Heroic
  • 980
  • 4
  • 12
-1

There is Two options:

a = [2,34,55,1,22,11,22,55,1]

#First option using sorted and set. 
sorted(set(a))

#second option using list and set.
list(set(a))
Anil Kesariya
  • 1,044
  • 1
  • 7
  • 13