Bruno Desthuilliers wrote: > If you want to prevent this from happening and don't mind creating a > copy of the list, you can use the sorted() function with the key and > reverse arguments and operator.itemgetter: > > >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), > ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')] > >>> from operator import itemgetter > >>> sorted(lines, key=itemgetter(0), reverse=True) > [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), > ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]
You don't need to use sorted() -- sort() also takes the key= and reverse= arguments:: >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), ... ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ... ('1996', 'aaa')] >>> from operator import itemgetter >>> lines.sort(key=itemgetter(0), reverse=True) >>> lines [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')] STeVe -- http://mail.python.org/mailman/listinfo/python-list