Python: Range() maximum size; dynamic or static?

痞子三分冷 提交于 2019-12-06 04:53:09

问题


I'm quite new to python, so I'm doing my usual of going through Project Euler to work out the logical kinks in my head.

Basically, I need the largest list size possible, ie range(1,n), without overflowing.

Any ideas?


回答1:


Look at get_len_of_range and get_len_of_range_longs in the builtin module source

Summary: You'll get an OverflowError if the list has more elements than can be fit into a signed long. On 32bit Python that's 2**31 - 1, and on 64 bit Python that's 2**63 - 1. Of course, you will get a MemoryError even for values just under that.




回答2:


The size of your lists is only limited by your memory. Note that, depending on your version of Python, range(1, 9999999999999999) needs only a few bytes of RAM since it always only creates a single element of the virtual list it returns.

If you want to instantiate the list, use list(range(1,n)) (this will copy the virtual list).



来源:https://stackoverflow.com/questions/3247973/python-range-maximum-size-dynamic-or-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!