As mentioned by others Pythons sorted() function and the sort() method of a list provides the key parameter to specify a function to be called on each list element prior to making comparisons.
The key thing is that this key parameter is a function object that takes when it is called only one argument and returns exactly one value which is used for the sorting.
A anonymous "lambda" function is often used for this purpose, since its definition does not include a return statement and therefor always contains an one expression which is returned.
For instance
>>> myKey = lambda e: id(e)
creates an (anonymous) function object
>>> type(myKey)
<class 'function'>
which takes one argument and returns a value and would therefore be a valid key for sorting.
If you want to call the myKey function object now you would simply do this:
>>> myKey(42)
503732608
To solve your problem you could create a lambda function as key which takes an element and returns its index in the foo string to keep the order of the characters:
>>> foo = "Wicked long string"
>>> "".join(sorted(set(foo), key = lambda e: foo.index(e)))
'Wicked longstr'
On the other hand -- since foo.index is a function object itself which takes one argument and returns one value -- you could pass this object instead to the sorted() function and by-pass the lambda definition:
>>> "".join(sorted(set(foo),key = foo.index))
'Wicked longstr'
Hope this helps :)
.indexmethod, see docs.python.org/2/library/…set(which is unordered) using the original lists index. So you get the same order as the original list. Withoutkeyit would just sort the characters lexically..indexis, because it has nothing to do with.index(sub[, start[, end]]), does it?>>> for i in foo: print i.indexit returns every list element's original index?