If you need to iterate a digital sequence, you can use the range () function, and the range () function can generate an equal-difference series.
Example:
For I in range (5)
Print (I)
This code will output five numbers: 0, 1, 2, 3, and 4.
Range (10) produces 10 values. You can also start range () from another number, or define a different increment, or even a negative increment.
Range (5, 10) ranges from 5 to 9 (0, 10, 3) increment to three, including 100, -30) the increment is-30, including-10,-40,-70. range () and len () can be used together to iterate an index sequence, for example:
A = ['nina ', 'Jim', 'rainman ', 'Hello']
For I in range (len ()):
Print (I, a [I])
In fact, the principle of python range is to generate an array, and the following method is used:
For I in range (10 ):
Print I
In fact, the range () function is an array and returns the array result to in, that is, it is essentially an iteration.
Xrange
Xrange example:
- >>> Xrange (5)
- Xrange (5)
- >>> List (xrange (5 ))
- [0, 1, 2, 3, 4]
- >>> Xrange (1, 5)
- Xrange (1, 5)
- >>> List (xrange (1, 5 ))
- [1, 2, 3, 4]
- >>> Xrange (0, 6, 2)
- Xrange (0, 6, 2)
- >>> List (xrange (0, 6, 2 ))
- [0, 2, 4]
Through the above example, we can know that xrange in python is different from range in that xrange generates a generator instead of an array.