python - Removing Item From List - during iteration - what's wrong with this idiom? -
as experiment, did this:
letters=['a','b','c','d','e','f','g','h','i','j','k','l'] in letters: letters.remove(i) print letters
the last print shows not items removed ? (every other was).
idle 2.6.2 >>> ================================ restart ================================ >>> ['b', 'd', 'f', 'h', 'j', 'l'] >>>
what's explanation ? how re-written remove every item ?
some answers explain why happens , explain should've done. i'll shamelessly put pieces together.
what's reason this?
because python language designed handle use case differently. the documentation makes clear:
it not safe modify sequence being iterated on in loop (this can happen mutable sequence types, such lists). if need modify list iterating on (for example, duplicate selected items) must iterate on copy.
emphasis mine. see linked page more -- documentation copyrighted , rights reserved.
you understand why got got, it's undefined behavior can change no warning build build. don't it.
it's wondering why i += i++ + ++i
whatever hell line on architecture on specific build of compiler language -- including not limited trashing computer , making demons fly out of nose :)
how re-written remove every item?
del letters[:]
(if need change references object)letters[:] = []
(if need change references object)letters = []
(if want work new object)
maybe want remove items based on condition? in case, should iterate on copy of list. easiest way make copy make slice containing whole list [:]
syntax, so:
#remove unsafe commands commands = ["ls", "cd", "rm -rf /"] cmd in commands[:]: if "rm " in cmd: commands.remove(cmd)
if check not particularly complicated, can (and should) filter instead:
commands = [cmd cmd in commands if not is_malicious(cmd)]
Comments
Post a Comment