While loop in Python stopping before False

Viewed 51

I'm having a list of strings. I don't need some of the strings as it's a repeating header. I defined a function using while loop that should remove the strings, however I need to run the cell multiple times as the while loop stops before i=len(list_of_strings). If I run the cell multiple times, then it eventually works. What did I do wrong?

def header_eraser(list_of_strings):
    i=0
    while i < len(list_of_strings):
        if list_of_strings[i] in headers:
            del list_of_strings[i]
            i+=1
        else:
            i+=1
2 Answers

As Sayse said in a comment:

If you're deleting an index, you don't need to increment i since the next index will have moved to current position

i.e.

def header_eraser(list_of_strings):
    i = 0
    while i < len(list_of_strings):
        if list_of_strings[i] in headers:
            del list_of_strings[i]
            # i += 1  # <- Remove this line
        else:
            i += 1

However, you might find it easier to use a list comprehension, which requires returning a new list instead of modifying the existing one:

def header_eraser(list_of_strings):
    return [s for s in list_of_strings if s not in headers]

When you remove an element, the length of the list changes and therefore you are skipping some elements, that's why if you run it multiple times it works.

I would suggest a for loop here, so you don't have to worry abount indexes:

def header_eraser(list_of_strings):
    new_list = []
    for s in list_of_strings:
        if s not in headers:
            new_list.append(s)
    return new_list

This can also be written as a list comprehension:

new_list = [s for s in list_of_strings if s not in headers]
Related