Search code examples
pythondatelist-comprehension

Finding Min/Max Date with List Comprehension in Python


So I have this list:

snapshots = ['2014-04-05',
        '2014-04-06',
        '2014-04-07',
        '2014-04-08',
        '2014-04-09']

I would like to find the earliest date using a list comprehension.

Heres what I have now,

earliest_date = snapshots[0]
earliest_date = [earliest_date for snapshot in snapshots if earliest_date > snapshot]

When I print the earliest date, I expect an empty array back since all the values after the first element of the list are already greater than the first element, but I WANT a single value.

Here's the original code just to signify i know how to find the min date value:

for snapshot in snapshots:
    if earliest_date > snapshot:
        earliest_date = snapshot

Anyone has any ideas?


Solution

  • Just use min() or max() to find the earliest or latest dates:

    earliest_date = min(snapshots)
    lastest_date = max(snapshots)
    

    Of course, if your list of dates is already sorted, use:

    earliest_date = snapshots[0]
    lastest_date = snapshots[-1]
    

    Demo:

    >>> snapshots = ['2014-04-05',
    ...         '2014-04-06',
    ...         '2014-04-07',
    ...         '2014-04-08',
    ...         '2014-04-09']
    >>> min(snapshots)
    '2014-04-05'
    

    Generally speaking, a list comprehension should only be used to build lists, not as a general loop tool. That's what for loops are for, really.