Home  >  Article  >  Backend Development  >  Introduction to the use of range() function in Python (with code)

Introduction to the use of range() function in Python (with code)

不言
不言forward
2019-04-15 10:27:003232browse

This article brings you an introduction to the use of the range() function in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Range() is a built-in function of python. It is used in many places. Currently, I often use it as the number of loops in a for loop. In fact, the usage of range() is not only that. This article will give you introduce.

If you really need to iterate over a sequence of numbers, the built-in function <span class="pre">range()</span> will come in handy. It generates an arithmetic series:

>>> for i in range(5):
...     print(i)
...
01
2
3
4

The given terminal value is not in the sequence to be generated; <span class="pre">range(10)</span> will generate 10 values, and is Generate a sequence of length 10 with a legal index. The range can also start with another number, or increase by a specified amount (even a negative number; sometimes this is also called 'stepping')

range(5, 10)
   5, 6, 7, 8, 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

To iterate by the index of the sequence, you can <span class="pre">range()</span> and <span class="pre">len()</span> are combined as follows:

>>> a = [&#39;Mary&#39;, &#39;had&#39;, &#39;a&#39;, &#39;little&#39;, &#39;lamb&#39;]
>>> for i in range(len(a)):
...     print(i, a[i])
...
Mary
had
a
little
lamb

However, in most of these cases, use <span class="pre">enumerate()</span> function is more convenient, please see Looping Tips.

If you just print range, strange results will appear:

>>> print(range(10))
range(0, 10)

<span class="pre">range()</span> The object returned behaves in many ways like A list, but not really. This object returns consecutive items based on the desired sequence as you iterate over it, but it doesn't actually generate a list, which saves space.

We say that such an object is iterable, that is, suitable as a parameter for functions and structures that expect consecutive values ​​to be obtained from it before the end of the iteration element. We have seen that the <span class="pre">for</span> statement is such an iterator. Function <span class="pre">list()</span> is another one; it creates a list from an iterable object.

>>> list(range(5))
[0, 1, 2, 3, 4]

Later, we will see more functions that return iterable objects, and functions that take iterable objects as parameters. (Related recommendations: python tutorial)

The above is the detailed content of Introduction to the use of range() function in Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete