Say given a list s = [2,2,2,3,3,3,4,4,4]
I saw the following code being used to obtain unique values from s:
unique_s = sorted(unique(s))
where unique is defined as:
def unique(seq):
# not order preserving
set = {}
map(set.__setitem__, seq, [])
return set.keys()
I’m just curious to know if there is any difference between this and just doing list(set(s))? Both results in a mutable object with the same values.
I’m guessing this code is faster since it’s only looping once rather than twice in the case of type conversion?
You should use the code you describe:
This works on all Pythons from 2.4 (I think) to 3.3, is concise, and uses built-ins in an easy to understand way.
The function
uniqueappears to be designed to work ifsetis not a built-in, which is true for Python 2.3. Python 2.3 is fairly ancient (2003). Theuniquefunction is also broken for the Python 3.x series, sincedict.keysreturns an iterator for Python 3.x.