40Hz_ringtone 40Hz_ringtone - 18 days ago 10
Python Question

Appending to array while iterating over it

I'm trying to create a python script that loops through an array of entries and adds a new day object with a date if that date is not already in the date list.

entryList = [aDate,anotherDate,fooDate]
history = [aDate]

for entry in entryList:
for day in history[:]:
if day.date == entry.date:
break
else:
dayEntry = dayEntry()
dayEntry.date = entry.date
history.insert(0,dayEntry)
break


according to this: https://docs.python.org/3/tutorial/controlflow.html it should work, but I'm missing something.

thanks--

Answer

So you want to append to history the entries in entryList but only the first one for a given date?

I think this is a case for not any().

for entry in entryList:
    if not any(day.date == entry.date for day in history):
        dayEntry = dayEntry()
        dayEntry.date = entry.date
        history.insert(0,dayEntry)

not any(day.date == entry.date for day in history)

reads as: there isn't a day in history with this entry's date.

If the history is permitted to be a dictionary, where the keys are the entries' dates, rather than a list:

for entry in entryList:
    if entry.date not in history:
        dayEntry = dayEntry()
        dayEntry.date = entry.date
        history[dayEntry.date] = dayEntry
Comments