Python Range() Function Tutorial with Example

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, range() function from Python 3.x  works a little bit different from Python 2.x, but the concept is the same.

Python Range() Function Tutorial with Example

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.

Syntax 

A simple syntax of range function.

  • 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.

Output : 0
1
2
3
4

Example 2: print the numbers from 1 to 4, and print each item in the sequence:

Output: 1
2
3
4

Example 3: How to Increment by 3 instead of 1 in Python range() function.

Output: 1
4
7
10
13
16
19

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)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples Range() Function is in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.