It sometimes reverse when I turn a string into a set

Question:

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?

Asked By: Jethy11

||

Answers:

Sets are unordered. so try this.


from collections import Counter


x = 'ABBA'

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

print(x) # AB

Answered By: codester_09

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.

Answered By: C-3PO
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.