As mentioned by other Pythons functions, sorted() , and the sort() method of a list provides a key parameter to specify the function that must be called on each element of the list before comparisons are made.
The main thing is that this key parameter is a function object that takes when it is called with only one argument and returns exactly one value, which is used for sorting.
An anonymous lambda function is often used for this purpose, since its definition does not include the return and therefore always contains which is returned.
for instance
>>> myKey = lambda e: id(e)
creates an object (anonymous) of a function
>>> type(myKey) <class 'function'>
which takes one argument and returns a value and therefore the correct key to sort is.
If you want to call the myKey function object myKey , you simply do the following:
>>> myKey(42) 503732608
To solve your problem, you can create a lambda function as key , which takes an element and returns its index in the string foo to preserve the character order:
>>> foo = "Wicked long string" >>> "".join(sorted(set(foo), key = lambda e: foo.index(e))) 'Wicked longstr'
On the other hand, since foo.index is the function object itself, which takes one argument and returns one value, you can pass this object instead of the sorted() function and bypass the lambda definition:
>>> "".join(sorted(set(foo),key = foo.index)) 'Wicked longstr'
Hope this helps :)