Ali Ali - 7 months ago 44
Python Question

List of all unique characters in a string?

I want to append characters to a string, but want to make sure all the letters in the final list are unique.



Now of course I have two solutions in my mind. One is using a
that will map the characters with their ASCII codes. So whenever I encounter a letter it will set the index to
. Afterwards I will scan the list and append all the ones that were set. It will have a time complexity of O(n).

Another solution would be using a
and following the same procedure. After mapping every char, I will do the operation for each key in the dictionary. This will have a linear running time as well.

Since I am a Python newbie, I was wondering which would be more space efficient. Which one could be implemented more efficiently?

PS: Order is not important while creating the list.


The simplest solution is probably:

In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'

Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']

As far as performance goes, worrying about it at this stage sounds like premature optimization.