Skip to content

Instantly share code, notes, and snippets.

@juanarrivillaga
Last active November 5, 2020 06:22
Show Gist options
  • Save juanarrivillaga/550a8daf79a9813ff472b0d22290525f to your computer and use it in GitHub Desktop.
Save juanarrivillaga/550a8daf79a9813ff472b0d22290525f to your computer and use it in GitHub Desktop.
import collections
def drop(iterable, n):
iterator = iter(iterable)
buffer = collections.deque()
for _ in range(n):
try:
val = next(iterator)
except StopIteration:
return
buffer.append(val)
while True:
try:
val = next(iterator)
except StopIteration:
return
buffer.append(val)
yield buffer.popleft()
-------------------------------- Or more succinctly, with itertools ---------------------------------------
import collections
import itertools
def drop(iterable, n):
iterator = iter(iterable)
buffer = collections.deque()
buffer.extend(itertools.islice(iterator, n))
while True:
try:
val = next(iterator)
except StopIteration:
return
buffer.append(val)
yield buffer.popleft()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment