Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete item in a list using a for-loop

I have an array with subjects and every subject has connected time. I want to compare every subjects in the list. If there are two of the same subjects, I want to add the times of both subjects, and also want to delete the second subject information (subject-name and time).

But If I delete the item, the list become shorter, and I get an out-of-range-error. I tried to make the list shorter with using subjectlegth-1, but this also don't work.

   ...
   subjectlegth = 8
   for x in range(subjectlength):
        for y in range(subjectlength):
            if subject[x] == subject[y]:
                if x != y:
                    #add
                    time[x] = time[x] + time[y]
                    #delete
                    del time[y]
                    del subject[y]
                    subjectlength = subjectlength - 1
like image 823
kame Avatar asked Nov 29 '22 11:11

kame


1 Answers

Iterate backwards, if you can:

for x in range(subjectlength - 1, -1, -1):

and similarly for y.

like image 111
Chris Jester-Young Avatar answered Dec 05 '22 13:12

Chris Jester-Young