Stop for loop iteration trough a list at a certain point

Asked 1 month ago
Viewed 24 times

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?

asked 1 month ago

Correct Answer

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((v for v in vids if '&pkey=' in v), len(vids)):]
answered 1 month ago