Stop for loop iteration trough a list at a certain point

Advertisements

Basically I want that my for loop stops itself after a certain element in the list is being processed. Here is the code:

vids = [
    'https://www.itatv.com/ita_video.php?viewkey=626de171d928a',
    'https://www.itatv.com/ita_video.php?viewkey=6050c75748399',
    'https://www.itatv.com/ita_video.php?viewkey=6277dbe97910c',
    'https://www.itatv.com/ita_video.php?viewkey=5d660515990ec&pkey=150469821',
    'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
    'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
    'https://www.itatv.com/ita_video.php?viewkey=60dd6838ce483',
]

for v in vids:
    try:
        vids.remove(v)
        if '&pkey=' in v:
            raise StopIteration
    except StopIteration:
        break

print(vids)

The output is:

[
        'https://www.itatv.com/ita_video.php?viewkey=626de171d928a',
        'https://www.itatv.com/ita_video.php?viewkey=6050c75748399',
        'https://www.itatv.com/ita_video.php?viewkey=6277dbe97910c',
        'https://www.itatv.com/ita_video.php?viewkey=5d660515990ec&pkey=150469821',
        'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
        'https://www.itatv.com/ita_video.php?viewkey=6201e028e3811',
        'https://www.itatv.com/ita_video.php?viewkey=60dd6838ce483',
    ]

As you can see nothing changes, but i don’t know where my code is faulty. Does anyone have any suggestions?

>Solution :

The best way to go about this would probably be to create a new list which is basically a copy of the previous one from the wanted item onwards. There are many ways to do that but, probably the cutest one is the following:

new_list = vids[next((i for i, v in enumerate(vids) if '&pkey=' in v), len(vids)):]

What you are basically doing is:

  1. finding the first element that satisfies your condition by
    next((i for i, v in enumerate(vids) if '&pkey=' in v) and then
  2. slicing the list from that element onwards.

Note that if the string you are searching for does not exist, the new_list comes out empty ([]).

Also note, that the code as given above, also returns the element you are searching for (inclusive). If you want to make it exclusive, just add one (next((i+1..). The rest stays the same.

Leave a ReplyCancel reply