Home > Back-end >  Pop an item in list present in another list
Pop an item in list present in another list

Time:09-29

My problem is that I'm trying to remove element from list present in another list.

My list1 looks like this = [[6, 0, 3, 1, 5, 7, 8, 2, 4], [1, 5, 0, 4, 6, 2, 7, 8, 3]]
My list2 looks like this = [[1, 5, 2, 4, 6, 0, 7, 8, 3], [1, 5, 0, 4, 6, 2, 7, 8, 3], [1, 8, 2, 4, 0, 6, 7, 5, 3]]

And I want to continue with list1 which should look like this: [6, 0, 3, 1, 5, 7, 8, 2, 4]

My list2 will always be bigger list, because it saves a states which have been explored or visited. List1 have states that are possible. So an idea is that I want to work with list1 after being popped. I tried something like this:

for x in range(0, len(list2)):
   temp = list1[x]
   temp_h = temp.init_state

   if temp_h in list2:
       list1.pop(x)

But this wont work because of out of range index (which I understand). I havent got any ideas how to work with this.

CodePudding user response:

does this answer your question ?

list1 = [[6, 0, 3, 1, 5, 7, 8, 2, 4], [1, 5, 0, 4, 6, 2, 7, 8, 3]]
list2 = [[1, 5, 2, 4, 6, 0, 7, 8, 3], [1, 5, 0, 4, 6, 2, 7, 8, 3], [1, 8, 2, 4, 0, 6, 7, 5, 3]]

res = [item for item in list1 if item not in list2]
print(res) # [[6, 0, 3, 1, 5, 7, 8, 2, 4]]

CodePudding user response:

Most of the time when I come across a question like this, it is suggested to recreate the desired contents in a new list, as mentioned in this SO post. Here's a quick and dirty monkey patch solution for the lists you provided:

list1 = [[6, 0, 3, 1, 5, 7, 8, 2, 4], [1, 5, 0, 4, 6, 2, 7, 8, 3]]
list2 = [[1, 5, 2, 4, 6, 0, 7, 8, 3], [1, 5, 0, 4, 6, 2, 7, 8, 3], [1, 8, 2, 4, 0, 6, 7, 5, 3]]

print("This is list1 BEFORE pop: %s" % list1)
print("This is list2 BEFORE pop : %s" % list2)
print("%"*80)

while True:
    if not any(entry in list2 for entry in list1):
        break
    for i_1, item_1 in enumerate(list1):
        if item_1 in list2:
            list1.pop(i_1)
            continue

print("This is list1 AFTER pop: %s" % list1)
print("This is list2 AFTER pop: %s" % list2)
print("%"*80)

Result:

This is list1 BEFORE pop: [[6, 0, 3, 1, 5, 7, 8, 2, 4], [1, 5, 0, 4, 6, 2, 7, 8, 3]]
This is list2 BEFORE pop : [[1, 5, 2, 4, 6, 0, 7, 8, 3], [1, 5, 0, 4, 6, 2, 7, 8, 3], [1, 8, 2, 4, 0, 6, 7, 5, 3]]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
This is list1 AFTER pop: [[6, 0, 3, 1, 5, 7, 8, 2, 4]]
This is list2 AFTER pop: [[1, 5, 2, 4, 6, 0, 7, 8, 3], [1, 5, 0, 4, 6, 2, 7, 8, 3], [1, 8, 2, 4, 0, 6, 7, 5, 3]]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  • Related