---
description: What is Python Range? Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index
title: Python range() Function: Float, List, For loop Examples
image: https://www.guru99.com/images/python-range-function.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Python range() is a built-in function that generates an immutable sequence of integers from a start value up to, but not including, a stop value, using an optional step to control the increment.

* 🔘 **Syntax:** range(start, stop, step) accepts up to three integer arguments, where start defaults to 0 and step defaults to 1.
* ☑️ **Exclusive stop:** The sequence always stops one value before the stop index, so range(5) yields 0 through 4.
* ✅ **Step control:** A positive step increments the values, while a negative step counts backward for a reverse range.
* 🧪 **Type limits:** Only integers are accepted, so floating-point or string arguments raise a TypeError.
* 🛠️ **NumPy floats:** The NumPy arange() function extends range() behavior to floating-point sequences.
* 🤖 **AI workflows:** Machine learning code relies on range() to iterate training epochs, mini-batches, and hyperparameter grids.

[ Read More ](javascript:void%280%29;) 

![Python range\(\) Function](https://www.guru99.com/images/python-range-function.png)

## What is Python Range?

Python range() is a built-in function available with Python from Python (3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index is not given, the index is considered as 0, and it will increment the value by 1 till the stop index.

For example, range(5) will output the values 0, 1, 2, 3, 4\. The Python range() is a very useful command and is mostly used when you have to iterate using a [for loop](https://www.guru99.com/python-loops-while-for-break-continue-enumerate.html).

## Syntax

The syntax of the range() function is shown below:

range(start, stop, step)

### Parameters

* **start:** (optional) The start index is an integer, and if not given, the default value is 0.
* **stop:** The stop index decides the value at which the range function has to stop. It is a mandatory input to the range function. The last value will always be 1 less than the stop value.
* **step:** (optional) The step value is the number by which the next number in range has to be incremented; by default, it is 1.

### Return value

The return value is a sequence of numbers from the given start to stop index.

## Python range() Function and history

Python range() has been introduced from Python version 3; before that, xrange() was the function.

Both range() and xrange() are used to produce a sequence of numbers.

Following are the differences between range() and xrange():

| range()                                                                                              | xrange()                                                                                                                          |
| ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| The range() gives the sequence of numbers and returns a list of numbers.                             | The xrange() function gives a generator object that needs to be looped in a for-loop to get the values.                           |
| The range() returns a list.                                                                          | xrange() returns a generator object.                                                                                              |
| The range() method uses more memory as the list returned has to be stored in comparison to xrange(). | As xrange() returns a generator object, it does not give values instantly and has to be used inside a for-loop to get the values. |
| The usage of memory is more, hence the code execution is slow when working on a huge set of data.    | The code execution is faster using xrange().                                                                                      |

## Using range()

This example shows how to print the values from 0-9 using range().

The value used in range is 10, so the output is 0 1 2 3 4 5 6 7 8 9.

Since the start is not given, the start is considered as 0 and the last value is given till 9\. The last value is always 1 less than the given value, i.e. stop-1.

for i in range(10):
    print(i, end =" ")

**Output:**

0 1 2 3 4 5 6 7 8 9

## Using start and stop in range()

In the code, the start value is 3, and the stop value is 10\. Here the start index is 3, so the sequence of numbers will start from 3 till the stop value. The last value in the sequence will be 1 less than the stop value, 10-1 = 9.

for i in range(3, 10):
    print(i, end =" ")

**Output:**

3 4 5 6 7 8 9

## Using start, stop and step

The start value is 3, so the sequence of numbers will start at 3\. The stop value is 10, so the sequence of numbers will stop at (10-1), i.e. 9\. The step is 2, so each value in the sequence will be incremented by 2\. If the step value is not given, the value for step defaults to 1.

for i in range(3, 10, 2):
    print(i, end =" ")

**Output:**

3 5 7 9

So far, we have seen how the range() function gives the incremented value for the stop value given. Let us now try an example to get the decremented value in the range given.

## Incrementing the values in range using a positive step

The parameter step in range() can be used to increment or decrement the values. By default, it is a positive value, 1\. So it will always give incremented values.

The step value has to be positive in case you want incremented values as output.

for i in range(1, 30, 5):
    print(i, end =" ")

**Output:**

1 6 11 16 21 26

## Reverse Range: Decrementing the values using negative step

The parameter step with a negative value in range() can be used to get decremented values. In the example below, the step value is negative, so the output will be decremented from the range value given.

for i in range(15, 5, -1):
    print(i, end =" ")

**Output:**

15 14 13 12 11 10 9 8 7 6

The start value is 15, the stop value is 5, and the step value is a negative number, i.e. -1\. With the above inputs, the range() function will decrement the value from 15 onwards till it reaches the stop value, but here the difference is that the last value will be stop + 1.

## Using floating numbers in Python range()

Let us now work on the range() using floating-point numbers.

**Example:**

for i in range(10.5):
    print(i, end =" ")

In the above example, we have used the stop value as 10.5.

The output is:

Traceback (most recent call last):
  File "python_range.py", line 1, in <module>
    for i in range(10.5):
TypeError: 'float' object cannot be interpreted as an integer

Python gives an error as the range() function does not support floating-point numbers for start, stop, and step.

## Using for-loop with Python range()

In this example, we will use an array of numbers and see how to iterate the array inside a for-loop using range().

**Example:**

arr_list = ['Mysql', 'Mongodb', 'PostgreSQL', 'Firebase']

for i in range(len(arr_list)):
    print(arr_list[i], end =" ")

**Output:**

MysqlMongodb PostgreSQL Firebase

In the above example, we have used len(arr\_list) as the stop value. The for loop will iterate till the stop value, i.e. the length of the array, which will be 4, as we have four items in the arr\_list. The start value will be 0 and step will be 1, so the values will start from 0 and will stop at 3, i.e. length of array -1, meaning 4 -1 = 3.

### RELATED ARTICLES

* [Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key ](https://www.guru99.com/python-tuples-tutorial-comparing-deleting-slicing-keys-unpacking.html "Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key")
* [Python Internet Access using Urllib.Request and urlopen() ](https://www.guru99.com/accessing-internet-data-with-python.html "Python Internet Access using Urllib.Request and urlopen()")
* [Live Python Project: Join FREE ](https://www.guru99.com/live-python-project.html "Live Python Project: Join FREE")
* [How to Square a Number in Python (6 ways) ](https://www.guru99.com/python-square.html "How to Square a Number in Python (6 ways)")

## Using Python range() as a list

In this example will see how to make use of the output from range as a list.

Example:

print(list(range(10)))

**Output:**

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can see the output is a list format. It was not necessary to loop the range() and using list() method we could directly convert the output from range to list format.

## Using characters in python range()

So far, we have used integers in python range(). We have also seen that floating-point numbers are not supported in python range. Let us try and see the output as to what happens when we use characters.

Example:

for c in range ('z'):
        print(c, end =" ")

Output:

Traceback (most recent call last):
  File "python_range.py", line 1, in <module>
    for c in range ('z'):
TypeError: 'str' object cannot be interpreted as an integer

It throws an error saying a string cannot be interpreted as an integer.

To get the list of the alphabets you can customize the code and get the desired outputas shown below:

Example:

def get_alphabets(startletter, stopletter, step):
    for c in range(ord(startletter.lower()), ord(stopletter.lower()), step):
        yield chr(c)

print(list(get_alphabets("a", "h", 1)))

**Output:**

['a', 'b', 'c', 'd', 'e', 'f', 'g']

## How to Access Range Elements

You can make use of a for-loop to get the values from the range or use the index to access the elements from range().

### Using for-loop

Example:

for i in range(6):
    print(i)

**Output:**

0
1
2
3
4
5

### Using index

The index is used with range to get the value available at that position. If the range value is 5, to get the startvalue, you can use range(5)\[0\] and the next value range(5)\[1\] and so on.

**Example:**

startvalue = range(5)[0] 
print("The first element in range is = ", startvalue) 

secondvalue = range(5)[1] 
print("The second element in range is = ", secondvalue) 

lastvalue = range(5)[-1]
print("The first element in range is = ", lastvalue)

**Output:**

The first element in range is =  0
The second element in range is =  1
The first element in range is =  4

### Using list()

This method will print all the elements from the range(). Using list() it will return the elements from range() in list format.

Example:

print(list(range(10)))

**Output:**

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

It gives the list output for the range given.

## Example: Get even numbers using range()

Using range() will get the list of even numbers in the range given as input. The parameters for range() are: start is 2, stop is 20, and step is 2, so the values will be incremented by 2 and will give even numbers till stop-2.

**Example:**

for i in range(2, 20, 2):
    print(i, end =" ")

**Output:**

2 4 6 8 10 12 14 16 18

## Merging two-range() outputs

In this example, we will concatenate 2 range() functions with the help of the itertools module chain() function.

**Example:**

from itertools import chain

print("Merging two range into one")
frange =chain(range(10), range(10, 20, 1))
for i in frange:
    print(i, end=" ")

**Output:**

Merging two range into one
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

## Using range() With NumPy

The NumPy module has an arange() function that works and gives similar output like range(). The arange() takes in the same parameters as range().

Syntax:

arange(start, stop, step)

To work with NumPy, follow the steps given below.

**Step 1**: Import NumPy module

import numpy

In case, while execution, it gives an error saying numpy module not found, you need to install the module as shown in step 2.

**Step 2**: Install NumPy

pip install numpy

**Step 3**: Working Example of arange() using NumPy

import numpy as np

for  i in np.arange(10):
   print(i, end =" ")  

**Output:**

0 1 2 3 4 5 6 7 8 9

### Floating point numbers using NumPy arange()

It is not possible to get the floating-point sequence using range(), but it is possible using NumPy arange().

**Example:**

The range that we want is from 0.5 to 1.5\. The value will be incremented by 0.2.

import numpy as np

for  i in np.arange(0.5, 1.5, 0.2):
   print(i, end =" ")  

**Output:**

0.5 0.7 0.8999999999999999 1.0999999999999999 1.2999999999999998

The output we get is a little weird; some of the float numbers are shown with 16 decimal places. This happens because of the complexity of storing decimal floating numbers in binary format. You can also round the values if required and limit them to the decimal places you need.

## FAQs

🔢 Does Python range() return a list or a range object?

In Python 3, range() returns a lazy, immutable range object, not a list. It generates numbers on demand. Wrap it in list(range(n)) when an actual list is required. Python 2 returned a full list.

🎯 Why does range() exclude the stop value, and how do I include it?

The stop value is exclusive so that range(len(items)) maps cleanly to zero-based indexes. To include the endpoint, add one to the stop, for example range(1, 11) to count from 1 through 10.

🚫 Can the step argument in range() be zero?

No. Calling range(0, 10, 0) raises ValueError: range() arg 3 must not be zero, because a zero step could never reach the stop value and would loop forever. Use a positive or negative step instead.

🔬 How can I generate a range of floating-point numbers without NumPy?

range() rejects floats, but a list comprehension can scale integers: \[x \* 0.5 for x in range(0, 6)\] produces 0.0 to 2.5\. This avoids importing NumPy while still stepping through decimal values.

💾 Is the range() object memory-efficient for large sequences?

Yes. A range object stores only its start, stop, and step values, so range(1000000) uses the same tiny, constant amount of memory as range(10). Values are computed one at a time during iteration.

🔎 How do I check whether a number exists in a range()?

Use the in operator: 5 in range(0, 10) returns True. For range objects, Python performs this membership test with fast arithmetic in constant time rather than scanning every element, so it stays efficient on huge ranges.

🤖 How is range() used in AI and machine learning workflows?

Machine learning code uses range() to loop over training epochs, iterate mini-batches, and build hyperparameter grids. NumPy arange() and linspace() extend this to floating-point ranges for learning-rate schedules and threshold sweeps common in AI experiments.

⚙️ Can GitHub Copilot generate Python range() loops?

Yes. AI coding assistants such as GitHub Copilot autocomplete range()-based loops from a comment or function name, and agentic tools can refactor index loops into cleaner enumerate() or comprehension patterns, though the generated bounds still need a quick review.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-range-function.png","url":"https://www.guru99.com/images/python-range-function.png","width":"700","height":"250","caption":"Python range() Function","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/python-range-function.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/python-range-function.html","name":"Python range() Function: Float, List, For loop Examples"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/python-range-function.html#webpage","url":"https://www.guru99.com/python-range-function.html","name":"Python range() Function: Float, List, For loop Examples","dateModified":"2026-07-10T13:24:56+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-range-function.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/python-range-function.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/logan","name":"Logan Young","description":"I'm Logan Young, an expert in Python, providing top-tier tutorials and guides to enhance your coding skills and streamline your learning journey.","url":"https://www.guru99.com/author/logan","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/logan-young-author.png","url":"https://www.guru99.com/images/logan-young-author.png","caption":"Logan Young","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Python","headline":"Python range() Function: Float, List, For loop Examples","description":"What is Python Range? Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/logan","name":"Logan Young"},"dateModified":"2026-07-10T13:24:56+05:30","image":{"@id":"https://www.guru99.com/images/python-range-function.png"},"copyrightYear":"2026","name":"Python range() Function: Float, List, For loop Examples","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Does Python range() return a list or a range object?","acceptedAnswer":{"@type":"Answer","text":"In Python 3, range() returns a lazy, immutable range object, not a list. It generates numbers on demand. Wrap it in list(range(n)) when an actual list is required. Python 2 returned a full list."}},{"@type":"Question","name":"Why does range() exclude the stop value, and how do I include it?","acceptedAnswer":{"@type":"Answer","text":"The stop value is exclusive so that range(len(items)) maps cleanly to zero-based indexes. To include the endpoint, add one to the stop, for example range(1, 11) to count from 1 through 10."}},{"@type":"Question","name":"Can the step argument in range() be zero?","acceptedAnswer":{"@type":"Answer","text":"No. Calling range(0, 10, 0) raises ValueError: range() arg 3 must not be zero, because a zero step could never reach the stop value and would loop forever. Use a positive or negative step instead."}},{"@type":"Question","name":"How can I generate a range of floating-point numbers without NumPy?","acceptedAnswer":{"@type":"Answer","text":"range() rejects floats, but a list comprehension can scale integers: [x * 0.5 for x in range(0, 6)] produces 0.0 to 2.5. This avoids importing NumPy while still stepping through decimal values."}},{"@type":"Question","name":"Is the range() object memory-efficient for large sequences?","acceptedAnswer":{"@type":"Answer","text":"Yes. A range object stores only its start, stop, and step values, so range(1000000) uses the same tiny, constant amount of memory as range(10). Values are computed one at a time during iteration."}},{"@type":"Question","name":"How do I check whether a number exists in a range()?","acceptedAnswer":{"@type":"Answer","text":"Use the in operator: 5 in range(0, 10) returns True. For range objects, Python performs this membership test with fast arithmetic in constant time rather than scanning every element, so it stays efficient on huge ranges."}},{"@type":"Question","name":"How is range() used in AI and machine learning workflows?","acceptedAnswer":{"@type":"Answer","text":"Machine learning code uses range() to loop over training epochs, iterate mini-batches, and build hyperparameter grids. NumPy arange() and linspace() extend this to floating-point ranges for learning-rate schedules and threshold sweeps common in AI experiments."}},{"@type":"Question","name":"Can GitHub Copilot generate Python range() loops?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI coding assistants such as GitHub Copilot autocomplete range()-based loops from a comment or function name, and agentic tools can refactor index loops into cleaner enumerate() or comprehension patterns, though the generated bounds still need a quick review."}}]}],"@id":"https://www.guru99.com/python-range-function.html#schema-1139361","isPartOf":{"@id":"https://www.guru99.com/python-range-function.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/python-range-function.html#webpage"}}]}
```
