abnormal string list behaviour in python -


this question has answer here:

    print difflist     line in difflist:         if ((line.startswith('<'))or (line.startswith('>')) or (line.startswith('---'))):             difflist.remove(line)     print difflist 

here, initially,

difflist = ['1a2', '> ', '3c4,5', '< staring', '---', '> starring', '> ', '5c7', '< @ ', '---', '> add ', ''] 

and expect of code print

['1a2', '3c4,5', '5c7', ''] 

but instead

difflist= ['1a2', '3c4,5', '---', '> ', '5c7', '---', ''] 

when iterating on list, python keeps integer index of array element it's pointing to. however, when remove current element, of later elements shift lower index. position index gets incremented before "see" element shifted take place of element removed.

ultimately, better done list comprehension:

difflist = [ line line in difflist if not line.startswith(('<','>','---'))] 

if need operation in place use slice assignment on left hand side:

difflist[:] = [ line line in difflist if not line.startswith(('<','>','---'))] 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -