Educative Answers Team

The ** xrange()** function in Python is used to generate a sequence of numbers, similar to the

`range()`

function. However, `xrange()`

is used only in `range()`

is used in The general syntax for defining the xrange is:

```
xrange(start,end,step)
```

This defines a range of numbers from start(inclusive) to end(exclusive).

The range function can take three parameters:

**Start**: Specify the starting position of the sequence of numbers.**End**: Specify the ending position of the sequence of numbers**Step**: The difference between each number in the sequence.

It is must to define the end position. However, the start and step are optional. By default, the value of start is 0 and for step it is set to 1.

The `xrange()`

function creates a generator-like object that can be used in a `for`

loop to iterate over a range of numbers, similar to the `range()`

function in Python 3.

The following code explains how to define an `xrange()`

in Python:

`end`

is definedend=5x = xrange(end) #create a sequence of numbers from 0 to 4print(x)for n in x:print(n)

Example of xrange with a defined end only

**Line 1:**Here, the`end`

of the range is defined as 5.**Lines 2-3:**The var`x`

is pointing to the object created by the`xrange`

function in line 4.**Lines 4-5:**And then the`for`

loop is printing the sequence of values in the object.

`start`

and `end`

are definedstart=2end=5y = xrange(start,end) #create a sequence of numbers from 2 to 5print(y)for n1 in y:print(n1)

Example of xrange with start and end defined

**Lines 1-2:**Here, the`start`

of the range is defined as`2`

and the`end`

is defined as`5`

.**Lines 3-4:**The var`y`

is pointing to the object created by the`xrange`

function in line 6.**Lines 5-6:**And then the`for`

loop is printing the sequence of values in the object.

`start`

, `end`

, and `step`

are definedstart=2end=5step=2z = xrange(start,end,step) #create a sequence of numbers from 3 to 10 with increment of 2print(z)for n2 in z:print(n2)

Example of xrange with start, end and step defined

**Lines 1-3:**Here, the`start`

of the range is defined as`2`

, the`end`

is defined as`5`

and`step`

is defined as 2.**Lines 4-5:**The var`z`

is pointing to the object created by the xrange function in line 6.**Lines 6-7:**And then the`for`

loop is printing the sequence of values in the object.

The `xrange`

function generates numbers up to, but not including, the end parameter. So in our output, xrange(2, 6, 2) generates the numbers 2, 4, which are the numbers greater than or equal to 2, but less than 6, that are divisible by 2.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring

Related Courses