Range of Python sequence type

Range of Python sequence type

Overview

The range type represents an immutable sequence of numbers.
Usually used to loop a specified number of times in a for loop.

Range is a class type, and its class is defined as:

class range(stop)
class range(start, stop[, step])

The parameter of the range constructor must be an integer (it can be a built-in int or any object that implements the index special method).
If the step parameter is omitted, its default value is 1.

lst = range(1, 10)
print(lst, ' , ', list(lst))

Output:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/06.py
range(1, 10)  ,  [1, 2, 3, 4, 5, 6, 7, 8, 9]
Process finished with exit code 0

If the start parameter is omitted, its default value is 0.

lst = range(10)
print(lst, ' , ', list(lst))

Output:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/06.py
range(0, 10)  ,  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Process finished with exit code 0

If step is positive, the formula for determining the content of range r is r[i] = start + step i where i >= 0 and r[i] <stop.
If step is negative, the formula for determining the range content is still r[i] = start + step
i, but the restriction condition is changed to i >= 0 and r[i]> stop.

lst = range(0, -10, -1)
print(lst, ' , ', list(lst))

Output:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/06.py
range(0, -10, -1)  ,  [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
Process finished with exit code 0

If r[0] does not meet the value restriction, the range object is empty. The range object does support negative indexes, but it will be interpreted as indexing from the end of the sequence determined by the positive index.

lst = range(0)
print(lst, ' , ', list(lst))
lst2 = range(1, 0)
print(lst2, ' , ', list(lst2))

Output:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/06.py
range(0, 0)  ,  []
range(1, 0)  ,  []
Process finished with exit code 0

Set the step size and generate a sequence of numbers according to the given step size

lst = range(0, 30, 5)
print(lst, ' , ', list(lst))

Output:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/06.py
range(0, 30, 5)  ,  [0, 5, 10, 15, 20, 25]
Process finished with exit code 0

The range object implements all operations of the general sequence refer to the list , except for splicing and repetition (this is because the range object can only represent a sequence that conforms to the strict mode, and repetition and splicing usually violate this mode).

The advantage of the range type over regular list or tuple is that a range object always occupies a fixed amount of (smaller) memory

[Previous page] [Next page]

Guess you like

Origin blog.csdn.net/wzc18743083828/article/details/109758259