abnormal string list behaviour in python -
this question has answer here:
- remove items list while iterating 18 answers
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
Post a Comment