0

I am currently trying to write code for iterating through a list of tuples and if the names match check who is older and remove the younger one from the list. I am running into an issue where if I remove a tuple, the code still tries to iterate through the original range even though I update the variable l. Code:

dads = [('Jim', '30'), ('Jeff', '45'), ('Jim', '35')]
l = len(dads)
for i in range(l):
    for j in range(l):
        if dads[i][0] == dads[j][0]:
            if int(dads[i][1]) > int(dads[j][1]):
                dads.pop(j)
                l = len(dads)
                if j < i:
                    j -= 1
                    i -= 1
print(dads)

3 Answers3

0

You could use a while loop. Something like this:

oldest_dad = ('nobody', '0')
dads = [('Jim', '30'), ('Jeff', '45'), ('Jim', '35')]
while 0 < len(dads):
    if int(oldest_dad[1]) < int(dads[0][1]):
        oldest_dad = dads[0]
    dads.pop(0)
Rutger
  • 593
  • 5
  • 11
0

To make it a one liner:

new_dads=[y for y in dads if int(y[1])!=min([int(x[1]) for x in dads])]
SuperStew
  • 2,857
  • 2
  • 15
  • 27
0

You need to update you for loop

 for j in range(i):

Ultimately, here is the code

dads = [('Jim', '30'), ('Jeff', '45'), ('Jim', '35')]
l = len(dads)
for i in range(l):
     j in range(i):
        if dads[i][0] == dads[j][0]:
            if int(dads[i][1]) > int(dads[j][1]):
                dads.pop(j)
                l = len(dads)
                if j < i:
                    j -= 1
                    i -= 1
print(dads)