-1
table = [1, 10, 5]
table2 = [10]



def find_difference(a, b):  
    for items in a:
        print("yes")
        if items in b:
            print("happened")
            a.remove(items) *#breaks after this*
    return a


print(find_difference(table, table2))

I'm trying to find the difference between two list. After this function runs the 'runlog' only shows the word "yes" twice which means the for loop is breaking after the if statement executes. I re-arranged the 'table' list and put the 10 last to see if that was so, and it was. The 'runlog' shows the correct amount of "yes". This makes me believe it has to do directly with the remove() and pop() functions (since I tried them both). Again I'm not sure

CoderCode
  • 1
  • 4

3 Answers3

2

You cannot modify a list while you are iterating through it.

For your case, you need to for items in a.copy(): which will have you iterating through a copy of the list while deleting from the original list.

An alternative is to generate a list to_be_deleted containing those elements that you have determined need to be deleted from a. Then once you have existed from the for items in a: loop, you then delete the elements in a.

And of course, if you use sets rather than lists, Python has set difference as a built in operator.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
1

The reason is, you are removing an item from the list!

Why is that a problem? Well, when you remove an item from the list, the item after it shifts down into the place of the one you removed and so on and on for each item afterwards. That means when your for loop continues on, it doesn't print out any more "yeses" because there aren't any more positions for it to go through. Try instead:

table = [1, 10, 5]
table2 = [10]



def find_difference(a, b):
    for items in a.copy():
      print("yes",items)
      if items in b:
          print("happened")
          a.remove(items) #*breaks after this*
    return(a)


print(find_difference(table, table2))

This copies the a list and then when removing the value from the "true" a list, doesn't change the for loops length, thus giving you three "yeses"

Agent Biscutt
  • 712
  • 4
  • 17
0
table = [1, 10, 5]
table2 = [10]

If you want only the unique value from first table, you can use the below code,

uniquevaluesina = list(set(table).difference(set(table2)))

output: [1, 5]

If you want only the unique value from second table, you can use the below code,

uniquevaluesinb = list(set(table2).difference(set(table)))

output: []

If you want only the unique value from both the tables, you can use the below code,

uniquevaluesinbothlists = list(set(table2).symmetric_difference(set(table)))

output: [1, 5]