How does .index method of str work in python?

How does this code work?

values = ['1', '3', '9', '6', '7']  # just an example of what comes in
index = "123456789"["8" in values:].index  # everything except this line is understandable
print(sorted(values, key=index))

this kind of code looks very strange to me so i don’t understand how it works.

str[str in list:].index

Answer

This is needlessly complicated code. Either someone did something incorrectly, or they’re trying to be clever. Here’s what that line means:

index = "123456789"["8" in values:].index

Start with the "8" in values. This evaluates to False, because "8" is not in the values list. This is the same as:

index = "123456789"[False:].index

which, because False evaluates to 0, is just the same as:

index = "123456789"[0:].index

and because [0:] refers to the entire string, this:

index = "123456789".index

sets the variable index to point to the .index() method of the string "123456789". This is then used as the key to sorted() which has the effect of sorting values based on the index of each value in the "123456789" string.

In the end, this is the same as:

print(sorted(values))