Skip to content

Instantly share code, notes, and snippets.

@ischurov
Created November 14, 2016 21:54
Show Gist options
  • Save ischurov/028f2636c97f1e1a83f04ff10332a04d to your computer and use it in GitHub Desktop.
Save ischurov/028f2636c97f1e1a83f04ff10332a04d to your computer and use it in GitHub Desktop.

This is due to fact that you modify your list when iterating it. You can check what's going on with pythontutor.com visualizer or add some print statements like this:

    templist = ['', 'hello', '', 'hi', 'mkay', '', '']
    
    for i, element in enumerate(templist):
        print("Step", i)
        print('element is', repr(element), 'and templist is', templist)
        if element == '':
            print("element is empty")
            templist.remove(element)
            print("templist after remove", templist)
            
    
    print (templist)

Output:

    Step 0
    element is '' and templist is ['', 'hello', '', 'hi', 'mkay', '', '']
    element is empty
    templist after remove ['hello', '', 'hi', 'mkay', '', '']
    Step 1
    element is '' and templist is ['hello', '', 'hi', 'mkay', '', '']
    element is empty
    templist after remove ['hello', 'hi', 'mkay', '', '']
    Step 2
    element is 'mkay' and templist is ['hello', 'hi', 'mkay', '', '']
    Step 3
    element is '' and templist is ['hello', 'hi', 'mkay', '', '']
    element is empty
    templist after remove ['hello', 'hi', 'mkay', '']
    ['hello', 'hi', 'mkay', '']

You see, that on Step 1 you pick '' as element. This is the third element of the initial list, but for retrieves it on the Step 2 as we modified the list on Step 0 (removed first '') and now this second '' has index 1. We remove it at the end of Step 1.

Then on Step 2 we get element with index 3 ('mkay') thus skipping 'hi'.

Finally on Step 3 you pick the last '' (not the previous to last) as this is element with index ''. We skipped the previous to last element due to the same reason as we skipped 'hello' on Step 1.

After Step 3 the list is exhausted and we get out of for loop. This is why the last '' kept.

As for the solution which works, you can try this one:

    templist = [s for s in templist if s != '']

As well as other solutions like .filter().

@sophocles99
Copy link

Very helpful explanation, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment