Created
March 24, 2022 12:26
-
-
Save deven96/40326461edcb457064b1e8fc0da42baf to your computer and use it in GitHub Desktop.
Using itertools and generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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