TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Range() Function
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Range() Function

Last updated: Apr 23, 2024 7:00 pm
By Meenakshi Agarwal
Share
10 Min Read
Python range function explained
SHARE

Python range is one of the built-in functions available in Python. It generates a series of integers starting from a start value to a stop value as specified by the user. We can use it with a for loop and traverse the whole range like a list.

Contents
Syntax of Python range()1. range(stop)2. range(start, stop)Python range() function with examplesUse start, stop and step parametersUsing the negative start, stop, and step valuesGenerate range like an arithmetic seriesIterating a list using range()Convert range to listMake range inclusivePython range vs. xrange()Using index with Python range outputMerge output of two range() functionsKey Takeaways

Understand Python Range() Function

The range() function takes one required and two optional parameters. It works differently with different combinations of arguments. In this tutorial, we’ll walk you through the full functionality of the Python range function so that you can easily use it in your programming assignments.

For your information, the scope of this post is to cover the Python 3 range function and its usage. However, it briefly discusses the difference between older range versions (in Python 2).

Python range function explained

Syntax of Python range()

There are two variants of the Python 3 range() function. Let’s check their syntaxes one by one.

1. range(stop)

It is the most basic form of range(). It takes a single argument to specify the exclusive (stop – 1) upper limit.

‘0’ becomes the starting point here for number generation. See the below example.

robj = range(5)
for it in robj:
   print(it, end = ",")

# Result: 0,1,2,3,4,

Check out another example. The range with a ‘0’ stop value generates an empty range, i.e., zero elements.

r = range( 0 )
print( r )
print(len( r ))

# Result:
# range(0, 0)
# 0

If you provide a non-integer stop value, then it raises a TypeError.

range(1.1)

# TypeError: 'float' object cannot be interpreted as an integer

2. range(start, stop[, step])

It is a bit more sophisticated form of the range function. Here, you can generate a series of numbers with a common difference of your choice.

You can pass the following three arguments:

  • ‘start’ -> The initial value from which the range() generates a sequence of numbers, inclusive.
  • ‘stop’ -> The upper limit or the first value beyond which the range() concludes, and it’s excluded from the range() output.
  • ‘step’ -> The difference or increment between consecutive values in the range, determining the spacing between numbers.

Please note the following points while using range() with the above signature.

  • The default value of ‘step’ is 1. It comes into play when the step argument is missing.
  • A zero value for ‘step’ results in a ValueError.
  • A non-integer value causes a TypeError.
  • A non-zero integer step (>= stop) value would at least return a range with one element.

Please note that the range function only accepts integer arguments. To generate a float range, follow the below tutorial.

Must Read: Generate Float Range in Python

Python range() function with examples

Check out the below code examples to understand this function from depth:

Use start, stop and step parameters

# Range with two arguments
for it in range(1, 7):
   print(it, end = ", ")

# 1, 2, 3, 4, 5, 6,

print()
# Range with three arguments
for it in range(1, 7, 3):
   print(it, end = ", ")

# 1, 4,

Using the negative start, stop, and step values

We can pass negative values for all range parameters such as the start, stop, and step arguments.

In the below example, we are providing -ve values for the stop and step to iterate the loop in the reverse direction.

# Range with -ve values
for it in range(10, -1, -2):
   print(it, end = ", ")

# 10, 8, 6, 4, 2, 0

Generate range like an arithmetic series

Let’s produce an arithmetic series (i=10, n=100, d=10) using the range() method.

print(list(range ( 10, 100, 10 )))

# [10, 20, 30, 40, 50, 60, 70, 80, 90]

Range() object works as a generator. Hence, we’ve converted it into a list so that we can print the values on demand.

Iterating a list using range()

We can make use of the Python range() function to traverse a list. See the below example.

books = ['python', 'data science', 'machine learning', 'AI', 'deep learning']
size = len(books)
for it in range(0, size):
   print(books[it])

# python
# data science
# machine learning
# AI
# deep learning

Convert range to list

Python 3 range() produces a generator object. It fetches values one by one as the loop progresses instead of getting all of them at once.

In reality, the output of the range() function is an immutable sequence of integers. Hence, we can convert the same to a Python list. We’ll use the list constructor to convert range output to a list.

See the below example.

r = range ( 10, 100, 10 )
print(type( r ))
# <class 'range'>

r = list( r )
print(type( r ))
# <class 'list'>

print(r)
# [10, 20, 30, 40, 50, 60, 70, 80, 90]

Make range inclusive

The default nature of Python range() is to exclude the last number. Therefore, it always ignores the upper limit of its output.

However, we can make the following changes in our code to allow it.

  • Increment the stop value with the step counter
  • Pass the new stop value to the range() function

After making the above changes, let’s see what happens:

start = 0
stop = 7
step = 1

stop = stop + step

for it in range(start, stop, step):
   print(it, end = ", ")

# 0, 1, 2, 3, 4, 5, 6, 7

Python range vs. xrange()

We’ve outlined a few differences and some key facts about the range() and xrange() functions.

Python 2 used to have two range functions: range() and xrange()

  • The difference between the two is that range() returns a list whereas the latter results in an iterator.

In Python 3, we have only one range() function. It is an implementation of the xrange()function from the 2.0 version.

  • The new range() function neither returns a list nor an iterator. It gets a new type known as a range object.
  • We can iterate on the range object like a list. But it is a little different as we can’t slice it.
  • Unlike iterators, which produce one value at a time, the range() function gets all the numbers at once. Hence, it has a high memory requirement.
  • However, the range works faster with a small set of numbers.
# Require python 2.x
print(type(range(1)))
# type 'list'

# Require python 2.x
print(type(xrange(10)))
# class 'xrange'

# Require python 3.x
print(type(range(10)))
# class 'range'

Read more about Python xrange vs. range function.

Using index with Python range output

Yes, range() returns a unique object that has both list and generator-like properties.

Since it acts as a sequence, we can access its elements using the indexes. It allows both +ve and -ve index values.

# Indexing Python range object
print(range(0, 7)[1])
# 1
print(range(0, 7)[6])
# 6

Merge output of two range() functions

Python doesn’t have a built-in function to merge the result of two range() objects. However, we can still be able to do it.

There is a module named 'itertools' which has a chain() function to combine two range objects.

See the below example.

from itertools import chain

merged = chain(range(5), range(10, 15))
for it in merged:
   print(it, end = ", ")

# 0, 1, 2, 3, 4, 10, 11, 12, 13, 14

Key Takeaways

Here are some essential facts about the Python range() function:

  • It only allows integer-type numbers as arguments.
  • We can’t provide a string or float type parameter inside the range() function.
  • The arguments can either be +ve or -ve.
  • It doesn’t accept ‘0’ as a step value. If the step is ‘0’, the function throws a ValueError.
Learn Python Step-by-Step

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Search keys by values in a Python dictionary Search Keys by Value in a Dictionary
Next Article Generate float range of numbers in Python Generate Floating Point Range in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x