0

input: a = ['AAB', 'CAA', 'ADA']

(set(a[2]))                                      //**output is** {'A', 'D'}
list(set(a[2]))                                  // **output is** ['D', 'A']
''.join(list(set(a[2])))                         //**output is** 'DA'

How can I keep my order of string intact when I am applying list function to set ?

1 Answers1

1

Sets are not ordered in Python.

Use this recipe or just use a dict (which keeps the insertion order), ignoring the key (use some dummy object like None as a value).

In this example, the last line will always print ['y', 'x'] in that order.

d={}
d['y'] = None
d['x'] = None
print(list(d))

For your code, that would be dict.fromkeys(a[2], None)

(Dictionaries keep their insertion order in practice but unofficially from Python 3.6, and officially from Python 3.7 and on).

Community
  • 1
  • 1
Joshua Fox
  • 18,704
  • 23
  • 87
  • 147