# Getting a date range

I'm just trying to be more pythonic in my coding style and was wondering if this is a good way to get a list of seven days leading up to and including endDate:

daysDelta   = 6
lastSeven   = [endDate - datetime.timedelta(days=daysDelta)]
for x in range(1,7):
myOffset    = daysDelta - x
lastSeven.append(endDate - datetime.timedelta(days=myOffset))

-
Obligatory link: legacy.python.org/dev/peps/pep-0008 –  jonrsharpe Aug 14 '14 at 19:03
@jonrsharpe I'm not sure what you are pointing out, would be glad for clarification –  user3610360 Aug 14 '14 at 19:08
I'm suggesting you review the style guide and alter your code to match it. –  jonrsharpe Aug 14 '14 at 19:09

## 2 Answers

You've hard-coded both 6 and 7, which means that if you either need to change the range, you'll have to change both numbers. That's a bug waiting to happen.

The most Pythonic way would be to use a list comprehension, so that you define the entire list "at once", rather than appending one element at a time.

daysDelta = 6
lastSeven = [endDate - datetime.timedelta(days=days) for days in range(daysDelta, -1, -1)]

-
I'm not sure list comprehensions are inherently more pythonic. They are faster, but they are not very readable for anything non-trivial. –  mleyfman Aug 14 '14 at 19:16

There is an easy way to clean up your loop:

lastSeven = [endDate]
for x in range(1, 7):
lastSeven.append(endDate - datetime.timedelta(x))


Essentially, I am working backwards instead of forwards. This yields the correct dates, but in backwards order.

If you want them in chronological order do:

lastSeven.sort()


Also, just in case you don't like the sorting thing, here's a version which goes forwards:

lastSeven = [endDate - datetime.timedelta(7)]
for x in range(1, 7):
lastSeven.append(lastSeven[x-1] + dateTime.timeDelta(1))


Lastly, there are some issues with your coding style:

Don't write code like this:

shortName    = 3
veryLongName = 4


Write code like this:

shortName = 3
veryLongName = 4


Also, put a space between arguments (so foo(x, y) is correct, while foo(x,y) is not).

This is in line with PEP8, the python style guide

Lastly, you can use a list comprehension for a bit of extra speed as one of the answers suggests, but it comes at the cost of readability, which is something that Python strives to maximize over speed (usually).

Here are two below:

# go backwards, then sort
lastSeven = [endDate - datetime.timedelta(x) for x in range(7)].sort()

# go to start, then iterate forwards
startDate = endDate - datetime.timedelta(7-1)
lastSeven = [startDate + datetime.timedelta(x) for x in range(7)]

-
thanks for the style tips - definitely need to work on PEP8 –  user3610360 Aug 14 '14 at 19:16