A Python Range() Function (method) can create a sequence of the item at one time. It returns an item (numbers) between the start and stops Integers. One more important note, the range() function from Python 3.x works a little bit differently from Python 2.x, but the concept is the same.
This tutorial you will learn about Range() Function with examples.
Why Python Range() Function?
The inbuilt range() function in Python is useful to generate sequences of numbers in the form of a list.
A simple syntax of range function.
range(start, stop, step)
- start: Starting number of the sequence. (Default is 0)
- stop: Generate numbers up to, but not including this number.
- step: Difference between each number in the sequence. (Default is 1)
The all parameters are optional in range() function.
Examples of Python Range()
Example 1: Let’s Create a sequence of numbers from 0 to 4, and print() each item in the console.
xno = range(5) for n in xno: print(n)
Output : 0
Example 2: print the numbers from 1 to 4, and print each item in the sequence:
xno = range(1, 5) for n in xno: print(n)
Example 3: How to Increment by 3 instead of 1 in Python range() function.
x = range(1, 20, 3) for n in x: print(n)
Note some important rules:
- All parameters (start, stop, step) must be integers.
- Parameters can be positive or negative integers.
- Indexes start at 0, not 1.
Do comment in below, if you have any doubts and suggestions.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Examples Range() Function is in Python 3, so it may change its different from python 2 or upgraded versions.