pythondatetimeenumerate

Python enumerate for a datetime list


I want to move from the "i=0 ... i=i+1" construct to use Python enumerate. I'm having trouble with a list of datetime values. I understand that datetime objects (themselves) are not iterable (if that's the correct word) but I would think that a normal "list" of these objects would be iterable/enumerable. I must be wrong but I don't know why.

My original code:

import datetime

BIASList = [1.3719, 0.9861, 0.0782, 1.9248, 0.7429]

dList = [datetime.date(2017, 1, 19),
         datetime.date(2017, 1, 20),
         datetime.date(2017, 1, 21),
         datetime.date(2017, 1, 22),
         datetime.date(2017, 1, 23)]

i = 0
for d in dList:
    dom = d.strftime("%d")
    print(d, '   i = ', i, 'BIAS = ',
          BIASList[i],  'dom = ', dom)
    i = i + 1

produced

2017-01-19    i =  0 BIAS =  1.3719 dom =  19
2017-01-20    i =  1 BIAS =  0.9861 dom =  20
2017-01-21    i =  2 BIAS =  0.0782 dom =  21
2017-01-22    i =  3 BIAS =  1.9248 dom =  22
2017-01-23    i =  4 BIAS =  0.7429 dom =  23

My revised attempt at using enumerate was

import datetime

BIASList = [1.3719, 0.9861, 0.0782, 1.9248, 0.7429]

dList = [datetime.date(2017, 1, 19),
         datetime.date(2017, 1, 20),
         datetime.date(2017, 1, 21),
         datetime.date(2017, 1, 22),
         datetime.date(2017, 1, 23)]

i = 0
for count, d in dList:
    dom = d.strftime("%d")
    print(d, '   i = ', i, 'count = ', count, 'BIAS = ',
          BIASList[count],  'dom = ', dom)
    i = i + 1

The error was listed as

  File ...\untitled0.py:21 in <module>
    for count, d in dList:

TypeError: cannot unpack non-iterable datetime.date object

Solution

  • You need to call enumerate with dList as the argument. enumerate will give you an iterable of tuples (the index and the original item), which you can use to produce the same i as in your original code without needing to actually initialize and increment i:

    for i, d in enumerate(dList):
        dom = d.strftime("%d")
        print(d, '   i = ', i, 'BIAS = ',
              BIASList[i],  'dom = ', dom)
    

    If you're just trying to iterate over two lists in parallel, an even easier option is zip:

    for d, b in zip(dList, BIASList):
        dom = d.strftime("%d")
        print(f"{d}  BIAS = {b}  dom = {dom}")
    

    and if you want to print that i for some other reason you can combine enumerate and zip:

    for i, (d, b) in enumerate(zip(dList, BIASList)):
        dom = d.strftime("%d")
        print(f"{d}  i = {i}  BIAS = {b}  dom = {dom}")