Search code examples
pythonpandaslistdatetimeseries

List items not updating outside of for loop



I have a pandas series of dates in string format, but some of the values are a non-date string. I tried updating them individually to circumvent the non-date strings, but even though the values appear to be changed inside the for loop, the list remains unchanged once printed out of the loop.
diedlist = df['Died'].tolist()
for item in diedlist:
    if item == '(living)':
        continue
    print(item)
    item = dt.datetime.strptime(item, ("%b %d, %Y"))
    print(item)

The initial print(item) prints out the date in the existing format MMM DD, YYYY.
The print(item) after the strptime() function prints out the date in the new date format ("%b %d, %Y") , and returns a datetime object of YYYY-MM-DD as expected.
However, upon printing the list outside the loop, the items appear in their old format once again, as if untouched.
thank you for your help in advance.


Solution

  • You need to put the item back in the list:

    for index, item in enumerate(diedlist):
        if item == '(living)':
            continue
        item = dt.datetime.strptime(item, ("%b %d, %Y"))
        diedlist[index] = item