Python Forum

Full Version: sorted function example mystery
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The following code works, but I don't know why (I'm using python v 3.7.3)

print(f'{"".join(sorted("foo", key="of".index))}')
It correctly prints oof

I don't understand:
key="of".index
"of".index is the index function of str.
It return the index of an element. The function takes an element, which must be inside the str.
If not, it will raise a ValueError.

The key function is called for each char in the str (str is iterable).
The sort order is defined as follows: o == 0 and f == 1
This means, that after sorting, the o comes first, then the f.

It's a strange way to get a custom defined sorting order for str.
To illustrate DeaD_Eye answer with code:

>>> 'of'.index('f')
1
>>> 'of'.index('o')
0
>>> 'of'.index('a')
/.../
ValueError: substring not found
Thanks guys. I'm studying Python by working through coding problems from codewars.com
It's a good site as there are many code examples of the same problem to look at.
This example snippet you've posted is an Anti-pattern.
The sense behind f-strings are to make it easier readable and not to save lines of code.

def my_keyfunc(char):
    """
    Return the index of the string "of"
    """
    return "of".index(char)

sorted_str = "".join(sorted("foo", key=my_keyfunc))
print(f'This is the sorted_str: {sorted_str}')