0

I have this code:

for lineSDR in sorted_dates_removed:
  for lineFFL in final_to_find_list:
    if lineSDR in lineFFL:
      index1= final_to_find_list.index(lineFFL)
      final_to_find_list.pop(index1)

When I print this the final_to_find_list had doubled instead of gotten smaller. It is my understanding that the for loop and the "pop" combo is causing the indices to change each time the for loop starts again. I don't know that may be wrong, but it is not doing what I want which is to take the strings that match between both lists OUT of final_to_find_list. Thanks

list1= ['a','b','c','d','e']
list2= ['a','b','c','d','e','f']

for line1 in list1:
    for line2 in list2:
        if line1 in line2:
            index1= list2.index(line2)
            list2.pop(index1)

This prints ['f']. But for some reason it doesn't work for my larger lists.

PhysicsBish
  • 103
  • 4
  • Are the strings exact matches? – Nick Jun 14 '20 at 03:09
  • 1
    Does this answer your question? [Remove all the elements that occur in one list from another](https://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another) – Nick Jun 14 '20 at 03:13
  • 2
    It *really* helps in questions like this to provide a runable example that reduces the problem to its essence. As Nick's question above illustrates, we don't know what you mean by `that match between both`. Match in what sense? Is that a partial match like your code, or are you after something simpler? Input lists and desired output would make it much clearer. – Mark Jun 14 '20 at 03:14
  • @Nick Yes they are. – PhysicsBish Jun 14 '20 at 03:55
  • 2
    .pop() modifies the list. you should not do that when you have a for loop iterating over that same list. One approach is to save the indexes to remove from line 2 in a set, then when the loops complete, remove the indexed items from list 2. (starting at the end and moving toward the front, otherwise the indexes will be incorrect after the first removal) – RufusVS Jun 14 '20 at 04:05

1 Answers1

-2

I'd suggest doing this as a list comprehension. Something like:

final_to_find_list = [
    ffl for ffl in final_to_find_list 
    if not any(sdr in ffl for sdr in sorted_dates_removed)
]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • This is basically the same nested loop as in the OP, without the complexity of modifying the list as you go. It's possible to optimize by using a set, but if either list is fairly short the difference is negligible. – Samwise Jun 14 '20 at 15:31