0

why is the order different in the below.

Edit:

Also what is the correct solution for this,i.e, remove duplicates and preserve order

def rt(s):
  s = list(s)
  print s
  print set(s)

print rt('abc')

Output

['a', 'b', 'c']
set(['a', 'c', 'b'])
None
Rajeev
  • 44,985
  • 76
  • 186
  • 285
  • 4
    Sets do not have any sense of order. – Anand S Kumar Aug 20 '15 at 13:13
  • 2
    What sort of solution are you looking for? Do you want to have an ordered set? – Zibi Aug 20 '15 at 13:16
  • 1
    possible duplicate of [How do you remove duplicates from a list in Python whilst preserving order?](http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order) – juanchopanza Aug 20 '15 at 13:38

4 Answers4

3

Because set isn't an ordered structures. Internally, a set uses a hash table, and there is no restriction that the hashed function maintain the ordering of its arguments.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

You can use OrderedSet, which serves your purpose.

Documentation

pip install orderedset


from orderedset import OrderedSet

def rt(s):
    s = list(s)
    print s
    print OrderedSet(s)

print rt('abc')
hspandher
  • 15,934
  • 2
  • 32
  • 45
1
def unique(sequence):
    seen = set()
    for e in sequence:
        if e not in seen:
            seen.add(e)
            yield e

Usage:

>>> ''.join(unique('aaabbddeffg'))
'abdefg'

See the itertools recipes for a slightly more efficient version, called unique_everseen.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

If you want to have a set with preserved order, you can look here for various solutions: Why are there no containers sorted by insertion order in Python's standard libraries?

If you want to eliminate the duplicates, and sort it you can use:

s = sorted(set(s))

From most inner call:

set - removes duplicates

sorted - sorts it in ascending order.

Also, you're missing a return statement, thus last print is None

Community
  • 1
  • 1
Zibi
  • 350
  • 1
  • 13