0

I am learning Python and have been finding that for some reason my for loop will stop, even when there is more 'loops' to go.

This happens ONLY when I delete an item from a list. If the removal is commented out, it works: printing "RUNNING LISTING" twice and it will check 2 items against 2 in the list. If an item is deleted it will print once and will check only 1 item agaisnt the other 2. Both times the console has no error.

It stops with an independant list variable when the original isnt affected: independant_list = looping_list. and also stops with list.remove(x), list.pop(x) and del list[x].

currently the problem code is: del listings_to_add[listing_count]

Here is my code, in short (I think):

for A in ListX:
    for B in ListY:
        if A in ListY:
            ListX - remove(A)
       

And in Long:

listings_to_add = new_listing_list
    for listing_count, listing in enumerate(new_listing_list):
        found = False
        print('\nRUNNING LISTING\n')

        #Checks the listing against all in DB
        for count, i in enumerate(id_in_DB):
            if not found:

                # Checks links - cuts them to listingID
                if str(listing[4]).split('?rsqid')[0] == i[1].split('?rsqid')[0]:
                    same_link = True
                    del listings_to_add[listing_count]
                    found = True
                else:
                    print(f'Different link: "{listing[4]}" \nWith DB.......: "{i[1]}"')

I have read other posts about why deleting from a list you are running through makes bugs, which is what I had done first, but it still stops after changes. Any help would be appreciated.

Ciribear
  • 5
  • 2
  • 2
    _"deleting from a list you are running through makes bugs"_: You are still doing it. `listings_to_add = new_listing_list` won't create a new list. Try `listings_to_add = new_listing_list[:]`. – Selcuk May 27 '21 at 04:04
  • I believe `list(new_listing_list)` would convey the intetin better than `new_listing_list[:]` – xvan May 27 '21 at 04:08
  • Btw, the short code makes no sense since you're not using `B`. – wjmolina May 27 '21 at 04:37

2 Answers2

0

you can use list comprehensions to tackle this

for A in ListX:
    for B in ListY:
        if A in ListY:
            ListX - remove(A)

as

listX = [x for x in listX if x not in listY]
Ali Aref
  • 1,893
  • 12
  • 31
0

Your problem is that you are iterating new_listing_list, but listings_to_add is an alias, so when you del listings_to_add[listing_count], you are affecting new_listing_list.

I decluttered your code. Try this:

listings_to_add = []
for listing_count, listing in enumerate(new_listing_list):
    for count, i in enumerate(id_in_DB):
        if str(listing[4]).split('?rsqid')[0] == i[1].split('?rsqid')[0]:
            same_link = True
            break
        listings_to_add.append(listing)
        print(f'Different link: "{listing[4]}" \nWith DB.......: "{i[1]}"')
wjmolina
  • 2,625
  • 2
  • 26
  • 35