0% found this document useful (0 votes)
43 views

Big Billion Prrinting in Python

This document discusses more efficient ways to iterate over large ranges in Python compared to using range(). It recommends using xrange() for ranges over 1 billion as it avoids creating a list. It also suggests using a generator expression or function instead of building a large list, to avoid memory overhead and allow iteration without storing all values. Yield can be used to generate values on demand instead of all at once.

Uploaded by

Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Big Billion Prrinting in Python

This document discusses more efficient ways to iterate over large ranges in Python compared to using range(). It recommends using xrange() for ranges over 1 billion as it avoids creating a list. It also suggests using a generator expression or function instead of building a large list, to avoid memory overhead and allow iteration without storing all values. Yield can be used to generate values on demand instead of all at once.

Uploaded by

Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

1 if you have a really gigantic range you'd like to generate a list for, say

one billion, xrange is the function to use

https://www.pythoncentral.io/how-to-use-pythons-xrange-and-range/

https://stackoverflow.com/questions/15238250/fastest-way-to-count-up-to-1-billion-in-python

2
Usually, if you need to iterate up to 1000000000, there's some better way. For example, you can
use some mathematical property to avoid testing every number:

samplelist = [x**2 for x in range(int(1000000000**0.5))] # get all perfect squares up to 1000000000

you are adding a huge number of elements to a list, then consider using
a generatorinstead. This will avoid the overhead of creating a massive list, while still
being useful for many things

def gen_numbers(n):
for i in range(n):
if <i passes test>:
yield i

for i in gen_numbers(1000000000):
print(i)

-----------------------------------------------------------------------------------------------------------------------------------

Dont have a lot of python/programming experience. I need to test every number


between 1 and 1 billion, then append certain numbers to a list. Currently I'm trying to use
range( 0 , Billion ) , but i find that it takes about ~80 secs to do on my machine with
Python 3.3. Is there a much more efficient method to do this?

for i in range(0, Billion)


# if i passes test
samplelist.append(i)
-----------------------------------------------------------------------------------------------------------------------------------

You might also like