The easiest way is to use set()
:
>>> mj = [2, 4, 4, 4, 4, 4, 9, 9]
>>> mj2 = set(mj1)
>>> mj2
set([9, 2, 4])
>>> list(mj2)
[9, 2, 4]
If you want to maintain order (since the sets
are a unordered list of elements), you can pass a sort
at the end:
>>> sorted(list(mj2))
[2, 4, 9]
Another option, if your list is originally sorted and you want to maintain order, you can use the class OrderedDict
and take advantage of it to maintain this order:
>>> from collections import OrderedDict
>>> OrderedDict.fromkeys(mj)
OrderedDict([(2, None), (4, None), (9, None)])
>>> OrderedDict.fromkeys(mj).keys()
[2, 4, 9]
OrderedDict
is an implementation of the dictionaries that allows you to "remember" the order in which your elements have been inserted. Therefore, you can use the fromkeys
dictionary method to use the elements of mj
as the dictionary keys, since the elements of mj
are previously sorted then the order is maintained.