Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

range
functions
python
loops
iterator

How to use the range function in Python

Educative Answers Team

What is the range() function?

The range function in Python generates a random list of numbers which is generally used to iterate over items using for loops.

Uses cases:

A range function might be called:

  • When an action needs to be performed N number of times.

  • In order to iterate over any iterable object.

Range() parameters

The range() function has two sets of parameters:

  • range(stop)

  • range(start, stop, step)

Here is what these terms mean:

Start: Starting number of the sequence.

Stop: Generate integers (whole numbers) up to, but not including this number.

Step: Difference between each number in the sequence.

Note: All parameters must be integers and can either be positive or negative.

range() is 0-index based, meaning list indexes start at 0, not 1.

1 of 6

Implementation

Now let’s take a look at an example implementing the range() function.

# One parameter
print "Sequence with One parameter"
for i in range(4):
  print(i)

# Two parameters
print "Sequence with Two parameters"
for i in range(2, 8):
  print(i)

# Three parameters
print "Sequence with Three parameters"
for i in range(5, 12, 3):
  print(i)

# Going backwards
print "Backward Sequence"
for i in range(20, -10, -5):  
  print(i)
    
# iterating a list
print "Printing List Elements"
mylist = ['alpha', 'bravo', 'charlie']
for i in range(0, len(mylist)): #len function calculates the length of the list  
  print(mylist[i])

RELATED TAGS

range
functions
python
loops
iterator
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring