jsetting32
jsetting32

Reputation: 1632

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?

Upvotes: 6

Views: 30259

Answers (3)

Prarthan Ramesh
Prarthan Ramesh

Reputation: 314

If you have any issue while sorting the list you can convert the list elements to date and find the max/min of it

from dateutil import parser
snapshots = ['2014-04-05',
        '2014-04-06',
        '2014-04-07',
        '2014-04-08',
        '2014-04-09']

snapshots = [parser.parse(i).date() for i in snapshots ]

max_date = max(snapshots )
min_date = min(snapshots )
print(max_date)
print(min_date)

Upvotes: 0

Andy
Andy

Reputation: 50540

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

>>> min(snapshots)
2014-04-05

You can use the min function.

However, this assumes that your date is formatted YYYY-MM-DD, because you have strings in your list.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121416

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.

Upvotes: 22

Related Questions