I have this function. It return range dates from today, but I need to use this result twice. If I replace 'yield' with 'return' I got TypeError: 'datetime.date' object is not iterable
def date_range():
start_date = datetime.date.today()
end_date = start_date + datetime.timedelta(days=11)
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
Rather than 'fix' the function, convert the result of the function to a list:
The
list()
function then iterates over all the results produced by the generator function and builds a list object from them. You can then iterate over that list object as many times as you like.The alternative would be to convert the function to return a list rather than generate the date objects one by one:
This uses a list comprehension to produce the whole list from the same loop. Note that the
end_date
calculation was entirely redundant since you then go back to a timedelta and even to an integer number of days!Similarly, your generator function version can be simplified to: