Confused by output from simple Python loop -
Confused by output from simple Python loop -
i have list of items , want remove items containing number 16 (here string, ind='16'). list has 6 items '16' in , yet loop consistently removes 5 of them. puzzled (i ran on 2 separate machines)!
lines=['18\t4', '8\t5', '16\t5', '19\t6', '15\t7', '5\t8', '16\t8', '21\t8', '20\t12', '22\t13', '7\t15', '5\t16', '8\t16', '21\t16', '4\t18', '6\t19', '12\t20', '8\t21', '16\t21', '13\t22'] ind='16' query in lines: if ind in query: lines.remove(query)
subsequently, typing 'lines' gives me: ['18\t4', '8\t5', '19\t6', '15\t7', '5\t8', '21\t8', '20\t12', '22\t13', '7\t15', '8\t16', '4\t18', '6\t19', '12\t20', '8\t21', '13\t22']
i.e. item '8\t16' still in list???
thank you
clive
it's bad thought modify list iterating over, removing item can confuse iterator. illustration can handled simple list comprehension, creates new list assign original name.
lines = [query query in lines if ind not in query]
or, utilize filter
function:
# in python 2, can omit list() wrapper lines = list(filter(lambda x: ind not in x, lines))
python
Comments
Post a Comment