Sitemap
Naga Sudhir

Naga Sudhir

I like programming for fun and adding value to people's lives

Create sequences with range function in python

2 min readAug 21, 2021

--

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision

Range is a python built-in sequence generator function through which we can generate sequences

Get Naga Sudhir’s stories in your inbox

Join Medium for free to get updates from this writer.

These sequences can be used in for loops and many other situations

Syntax

range(start, stop, step)

here start and step are optional parameters

  • start = optional input that specifies the number from which the sequence should start, default value is 0
  • stop = input that specifies the number at which the sequence should end
  • step = optional input that specifies the incrementation of sequence. default value is 1

Generating a sequence

# create a sequence from 0 to 4, i.e., 0,1,2,3,4
x = range(5)
# create a sequence from 1 to 7, i.e., 1,2,3,4,5,6,7
x = range(1,8)
# sequence from 2 to 12 with steps of 2, i.e., 2,4,6,8,10,12
x = range(2,13,2)

Creating a list from sequence

we can create list from sequence using * operator

# create sequence from 2 to 12 with steps of 2, i.e., 2,4,6,8,10,12
x = range(2,13,2)
# create a list from sequence using * operator
y = [*x]
print(y)
# this code should print [2,4,6,8,10,12]

Iterating over a sequence

Using in operator with for loop, we can iterate over each item of a sequence

# create sequence from 2 to 12 with steps of 2, i.e., 2,4,6,8,10,12
x = range(2,13,2)
# iterate over the sequence using for loop and in operator
for n in x:
print(n)
# this code should print 2,4,6,8,10,12 in each line of the console

--

--

Naga Sudhir
Naga Sudhir
0 followers

I like programming for fun and adding value to people's lives