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
  • 20,242
  • 46
  • 127
  • 187

4 Answers4

6

Use sorted():

sorted(set(a))

and you can omit the list() call entirely.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
1

Its simple Just use the sorted() method :

data = [10,5,46,4]
sorted_data = sorted(data)
print "Sorted Data ::::",sorted_data
Burhan Khalid
  • 161,711
  • 18
  • 231
  • 272
Anil Kesariya
  • 844
  • 1
  • 6
  • 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
  • 204,715
  • 48
  • 286
  • 369
Heroic
  • 960
  • 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
  • 844
  • 1
  • 6
  • 13