Hello. In this lesson we will learn about Python range function. Lets get started.
Python range Function
Python range function is used to generate sequences of numbers in list form. And Python’s range function only works for Integers. You can use Positive and negative values both.
Syntax
Here is the syntax for Python range() function.
range([start], stop [, step])
- start – The starting number of the sequence. This parameter is optional.
- stop – Just stop before this number. So, if the stop value is 9 then the list will end up with 8.
- step – The exact difference between each of the number in that sequence. This parameter is optional.
And keep in mind that:
Python’s range function is Zero-Index based. So the list index will start from 0.
Examples for Python range()
Here are some examples for Python range function:
>>> range(8) [0, 1, 2, 3, 4, 5, 6, 7] >>> range(5,15) [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> range(0, 20, 2) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> range(0, -20, -2) [0, -2, -4, -6, -8, -10, -12, -14, -16, -18]
You can also iterate through these lists ( generated by range function ). Here is a simple example:
for x in range(0, 20, 2): print(x)
And the output will be like this:
0 2 4 6 8 10 12 14 16 18
Hope this tutorial was helpful. Enjoy Python.
The post Python range Function tutorial appeared first on JS Tricks.