Search code examples
pythondate

Sort List of Tuples by Date element


I need the oldest people be first on the list, here is the example of the format i have to sort:

List =[ ('John', '12345', '1972-02-08'),
('Sara', '12345', '1977-07-01'),  
('Mario', '12345', '1971-06-13') ,   
('Lucas', '12345', '1967-04-27'),
('Kiara', '12345', '1973-02-15')]

Im new on python so i have some doubts on this. ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎


Solution

  • You can use sort(), sorted(), or datetime:

    from datetime import datetime as dt
    
    List = [
        ('John', '12345', '1972-02-08'),
        ('Sara', '12345', '1977-07-01'),
        ('Mario', '12345', '1971-06-13'),
        ('Lucas', '12345', '1967-04-27'),
        ('Kiara', '12345', '1973-02-15')
    ]
    
    print(sorted(List, key=lambda x: dt.strptime(x[2], '%Y-%m-%d')))
    print(sorted(List, key=lambda x: x[2]))
    

    Prints

    [('Lucas', '12345', '1967-04-27'), ('Mario', '12345', '1971-06-13'), ('John', '12345', '1972-02-08'), ('Kiara', '12345', '1973-02-15'), ('Sara', '12345', '1977-07-01')]
    [('Lucas', '12345', '1967-04-27'), ('Mario', '12345', '1971-06-13'), ('John', '12345', '1972-02-08'), ('Kiara', '12345', '1973-02-15'), ('Sara', '12345', '1977-07-01')]
    

    Comments

    • Since the dates are in ISO format, you can just sort them as strings, you don't need to parse them. – Barmar