Python Forum

Full Version: Sorting A List of Tuples Question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi... I am relatively new to Python.  I am trying to sort a list of tuples - each tuple contains a boolean variable and 
a string.  I'd like to use the list sort() method... I'm a little confused if I need to use a lambda or use key= or maybe 
even cmd=  I'd like to really do a comparison like cmp((is_present, element.text), (is_present, element.text)) or 
something similar to compare the tuples.  I'm just starting out in my journey with Python so any help or advice 
you can give would be great.
You can use .sort() to sort list of tuples without any parameters. Python sorts list of tuples lexicographically - at first it sorts it by first elements in tuples, then by second elements (if needed) and so on

So your tuples (bool, str) will be sorted by bool first (all tuples starting with False will be before any tuple starting with True) and then by str. If you need different sorting, you can use key parameter with either lambda or with other function (builtin or your own) - sort applies key function on items and sort is done by returned values.

Example:
Output:
In [1]: my_list = [(False, 'word'), (False, 'another word'), (True, 'third_word'), (True, "Uppercase word"), (False, "Word Uppercase")] In [2]: my_list.sort()   # "natural" tuple sort In [3]: print(my_list) [(False, 'Word Uppercase'), (False, 'another word'), (False, 'word'), (True, 'Uppercase word'), (True, 'third_word')] In [4]: my_list.sort(key=lambda x: (x[0], x[1].lower()) )   # case-insensitive sort In [5]: print(my_list) [(False, 'another word'), (False, 'word'), (False, 'Word Uppercase'), (True, 'third_word'), (True, 'Uppercase word')] In [6]: my_list.sort(key=lambda x: len(x[1]))   # sorted just by length of string In [7]: print(my_list) [(False, 'word'), (True, 'third_word'), (False, 'another word'), (False, 'Word Uppercase'), (True, 'Uppercase word')]
That is great... thanks so much.