0

The string is: x = 'ABBA'

whenever I use this code: x = 'ABBA' x = ''.join(set(x)) print(x)

It results in: BA but I want it to be the first letters instead of the second letters: AB

Is there any way that I can do it without using reverse function?

Jethy11
  • 13
  • 5
  • 1
    Sets are unordered. If you need the items in some specific order *but without duplicates*, then you can convert the set back into a list, sort that and go from there. – Joachim Sauer Nov 13 '22 at 10:48

2 Answers2

0

Sets are unordered. so try this.


from collections import Counter


x = 'ABBA'

x = "".join(Counter(x).keys())

print(x) # AB

codester_09
  • 5,622
  • 2
  • 5
  • 27
0

Sets in Python are still unordered unfortunately. However, dictionaries in newer versions of Python already preserve insertion order.

You can take advantage of this, by defining a dictionary with empty values, such that you can extract the keys in insertion order:

x = 'ABBA'
x = "".join({k:None for k in x}.keys())
print(x)
# AB

The idea is a bit hacky, but it works for now. Maybe in the future sets will also respect insertion order.

C-3PO
  • 1,181
  • 9
  • 17