python - A pythonic way to remove all instances of an element without generating a new list -
there many questions similar (here one) solutions i've seen use list comprehension or filter , ways generate new list (or new iterator in case of filter in python 3.x). there solutions remove instances modifying list (like this, and this), , last resort. however, asking see if there more elegant ("pythonic" question calls it) way of doing it.
why disregarding solutions generate new list: iterating on collection of lists, , python allows me modify "current" list iterating over, not replace entirely:
>>> ll= [[1,2,3], [2,3,4], [4,5,6]] >>> l in ll: if l[0] == 2: l = [10] >>> ll [[1, 2, 3], [2, 3, 4], [4, 5, 6]] #replacement didn't happen >>> l in ll: if l[0] == 2: l.remove(2) >>> ll [[1, 2, 3], [3, 4], [4, 5, 6]] #modification succeeded
you need use slice assignment replace list elements instead of list itself:
for l in ll: if l[0] == 2: l[:] = [10]
the [:]
part turns slice assignment; instead of replacing reference l
points to, replace all elements contained in l
new list.
demo:
>>> ll= [[1,2,3], [2,3,4], [4,5,6]] >>> l in ll: ... if l[0] == 2: ... l[:] = [10] ... >>> ll [[1, 2, 3], [10], [4, 5, 6]]
Comments
Post a Comment