2

Given this:

import datetime as dt

start_date = dt.date(2018,6,28)
steps_back = 4

Is there a way to implement the following using list comprehension in python ?

a_list = [start_date]

for i in range(1,steps_back):
    a_list.append(a_list[i-1] - dt.timedelta(7))

The result would look like this:

[datetime.date(2018, 6, 28),
 datetime.date(2018, 6, 21),
 datetime.date(2018, 6, 14),
 datetime.date(2018, 6, 7)]

where would you indicate the start value ?

error
  • 2,356
  • 3
  • 23
  • 25
AnarKi
  • 857
  • 1
  • 7
  • 27
  • 4
    You can't use the previous value in a list comprehension. You *could* do `[start_date - dt.timedelta(i * 7) for i in range(steps_back)]`, which recreates the first element but is otherwise relatively efficient. – jonrsharpe Jun 27 '18 at 08:37
  • Or `[start_date - dt.timedelta(i * 7) if i else start_date for i in range(steps_back)]`, which is slightly more efficient but arguably less easy to understand. – jonrsharpe Jun 27 '18 at 08:42
  • @jonrsharpe: why is your second solution is more efficient? – Azat Ibrakov Jun 27 '18 at 08:59
  • @AzatIbrakov because it doesn't rebuild the `start_date` to be the first element in the table, it uses the existing object. – jonrsharpe Jun 27 '18 at 09:09
  • @jonrsharpe: but it checks other `i` for "non-zeroness" – Azat Ibrakov Jun 27 '18 at 09:14
  • 1
    @AzatIbrakov well you could profile/time it if efficiency is really important, but an integer comparison is pretty well optimised. – jonrsharpe Jun 27 '18 at 09:16

0 Answers0