On 30 June 2013 07:06, Chris Angelico <ros...@gmail.com> wrote: > So, here's a challenge: Come up with something really simple, and > write an insanely complicated - yet perfectly valid - way to achieve > the same thing. Bonus points for horribly abusing Python's clean > syntax in the process.
This occurred to me out of the blue while working on something related. Here's a way to remove all instances of an element from an iterable. It's remarkably fast for it's course of action: from collections import deque from itertools import chain exhaust_iterable = deque(maxlen=0).extend def split_on(data, sentinel): chained = data = iter(data) while True: chunk = iter(chained.__next__, sentinel) yield chunk # Uses at least one item from chained, so "chained" and "data" are equivilant after this. # This is important as "data" is raw and thus will not get bogged down by pointless chain wrappings. # Yes, that is a premature optimisation. Go away. exhaust_iterable(chunk) # Throw StopIteration if not empty chained = chain([next(data)], data) def remove_all(iterable, victim): return list(chain.from_iterable(split_on(iterable, victim))) print(remove_all([1, 2, 1, 1, 0, 1, 2, 1, 1, 2, 2, 1, 0], 1)) and here it is again: from itertools import chain, repeat def remove_all(iterable, victim): iterable = iter(iterable) return list(chain.from_iterable(iter(chain([next(iterable)], iterable).__next__, victim) for _ in repeat(...))) print(remove_all([1, 2, 1, 1, 0, 1, 2, 1, 1, 2, 2, 1, 0], 1)) -- http://mail.python.org/mailman/listinfo/python-list