Skip to content

Instantly share code, notes, and snippets.

@deven96
Created March 24, 2022 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deven96/40326461edcb457064b1e8fc0da42baf to your computer and use it in GitHub Desktop.
Save deven96/40326461edcb457064b1e8fc0da42baf to your computer and use it in GitHub Desktop.
Using itertools and generators
import itertools
from memory_profiler import profile
@profile
def my_func():
a = [1] * (10 ** 6)
# A generator adds nothing to memory as each index is loaded
# on the fly
b = (2 for _ in range(2 * 10 ** 7))
# we discard the first 199999 from the generator using itertools
# and then call next() to access the 200000th which is what we want
c = next(itertools.islice(b, 199999))
return a.append(c)
if __name__=="__main__":
my_func()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment