Can someone explain how this sort result is produced?
<p>Lets say that you have the given function:</p>

<pre><code>def last(word):
    return word[-1]

print (sorted(['apple','orange','banana','grape','watermelon'], key=last))
</code></pre>

<p>This will return a list that is sorted by the last index in each string:</p>

<pre><code>['banana', 'apple', 'orange', 'grape', 'watermelon']
</code></pre>

<p>So now can someone explain what happens when we ask for user input to specify an index for each string that we are passing to our function <code>last</code>. For example if we change the code to be:</p>

<pre><code>def last(word):
    index = int(input('Enter index:'))
    return word[index]

print (sorted(['apple','orange','banana','grape','watermelon'], key=last))
</code></pre>

<p>Which then if the user inputs the following sequence (1,1,2,2,-1) it results in the list:</p>

<pre><code>['grape', 'banana', 'watermelon', 'apple', 'orange']
</code></pre>

<p>Which doesn't appear to be sorted by indexes 1, 2 or -1.</p>

<p>Can anyone explain what is going on behind the scenes and how Python is handling this case? I understand this a very strange question but I'd like to understand how Python is interpreting these instructions.</p>

<p>The sort is <em>exactly right</em>. You asked for the words to be sorted by indices <code>(1, 1, 2, 2, -1)</code>. Lets examine what characters those are:</p>

<pre><code>&gt;&gt;&gt; for index, word in zip((1, 1, 2, 2, -1), ['apple', 'orange', 'banana', 'grape', 'watermelon']):
...     print(word[index], word)
...
p apple
r orange
n banana
a grape
n watermelon
</code></pre>

<p>So the correct sorted order by those letters would be <code>('a', 'grape'), ('n', 'banana'), ('n', 'watermelon'), ('p', 'apple')</code> and <code>('r', 'orange'</code>) (where <code>('n', 'banana')</code> and <code>('n', 'watermelon')</code> are kept in input order as they both are sorted on <code>'n'</code>). This is exactly result you got.</p>

python sorting key