Python Range Example | range() Function Tutorial
Python Range Example | range() Function Tutorial is today’s topic. Python’s built-in range() method is handy when you need to perform an operation the specific number of times. Python range() method returns an immutable sequence of numbers between a given start integer to a stop integer. It creates a sequence of numbers from start to stop integer. By the end of this guide, you will understand the basics of range() function in python.
Python Range Example
Often you will want to use range() function when you want to perform an action let say x number of times, where you may or may not care about the index then this function is useful.
Sometimes you may want to iterate over the list or iterable object while being able to have the index available.
The syntax for range() method is following.
range(stop) range(start, stop[, step])
The range() takes mainly three arguments.
- start – integer starting from which the sequence of integers is to be returned
- stop – integer before which the sequence of integers is to be returned.
The range of integers ends at stop – 1.
- step (Optional) – integer value which determines the increment between each integer in the sequence.
It returns an empty sequence if the stop is negative or 0.
Let us see range() method’s example.
# app.py app = range(5) for data in app: print(data)
Now, see the output in the console.
The range() function returns the sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at the specified integer.
Now, let us add start and stop parameter and see the output.
# app.py app = range(6, 11) for data in app: print(data)
So, here we have started from number 6 to 11. But 11 here means 10 because it starts from 0. See the output below.
Let see one another example in which we add third parameter step and see the output.
# app.py app = range(6, 21, 3) for data in app: print(data)
So, it will print every third integer between 6 to 21.
Create a list of an even number using range()
Let us create a list of an even number using range() function.
# app.py app = range(6, 15, 2) appList = list(app) print(appList)
It will give the following output.
Provide negative step in range() function
Let see the scenario where we provide the negative argument of step and stop in range() method.
# app.py app2 = range(2, -15, -2) appList2 = list(app2) print(appList2)
In simple terms, range() function allows you to generate the series of numbers within the given range. It entirely depends on how many arguments you pass to the function, is it positive or negative arguments or you can decide where that series will begin and end as well as how big the difference will be between one number and the next by defining step parameter.
Finally, Python Range Example | range() Function Tutorial is over.