深度阅读

How to Use Python's xrange and range

作者
作者
2023年08月22日
更新时间
10.1 分钟
阅读时间
0
阅读量

The range() function is used to generate a sequence of numbers. It takes three arguments: start, stop, and step, and returns a sequence of numbers starting from start, up to but not including stop, in increments of step. Here are some examples:

To generate a sequence of numbers from 0 to 9:

for i in range(10):
    print(i)

This will print the numbers 0 through 9.

To generate a sequence of even numbers from 0 to 8:

for i in range(0, 10, 2):
    print(i)

This will print the even numbers 0, 2, 4, 6, and 8.

You can also convert the range() object into a list or tuple using the list() or tuple() constructor respectively.

In Python 2.x there is a similar function called xrange() that returns an object that generates the numbers on-the-fly instead of generating a full list at once, making it memory efficient for large ranges. However, it is not available in Python 3.x as the built-in range() function accomplishes the same.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。