tags:

views:

134

answers:

5

Given the code:

a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c

It prints:

['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]

Why does [('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')] change to [('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]?


Similarly, given:

c.sort(key=lambda x:3)#
print c

It prints:

[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]

Nothing changes - why?

+7  A: 

because x[1] means second

use

c.sort(key=lambda x:x[0])
Antony Hatchkins
+4  A: 

You've sorted c using the second item as the key, and the second item does indeed go up, just as you asked for it to go up. What's so surprising?!

Alex Martelli
+1  A: 
from operator import itemgetter    
c.sort(key=itemgetter(0))
S.Mark
A: 

You've sorted the list using the second element of each tuple as a key so you get the tuples ordered by their second element (Notice the 'a', 'b', 'c', 'd' in increasing order). What's the problem?

Noufal Ibrahim
+1  A: 

As the others have said, [1] refers to the second element, so the elements in the first part are sorted that way.

As for the second part, list.sort() is stable, so elements that evaluate to the same key will maintain their relative position in the sequence. This is why using .sort(reverse=True) can give different results from .sort() followed by .reverse().

Ignacio Vazquez-Abrams