When I run the following code to generate a list made of a range of numbers from 0 till 999 999 999. It raises a MemoryError
. What other way can I use to generate the same list but wont use up that much memory?
# Generate list
numbers = list(range(0,999999999))
# Add leading zeros
numbers = [str(x).zfill(9) for x in numbers]
CodePudding user response:
Use a generator:
numbers = (str(i).zfill(9) for i in range(999999999))
CodePudding user response:
Using a generator:
def generator(n):
i = 0
while i < n:
yield str(i).zfill(9)
i = 1
Usage:
for i in generator(5):
print(i)
Or, to create a list:
[i for i in generator(5)]