DEV Community

Cover image for Pythons range function
bluepaperbirds
bluepaperbirds

Posted on

1 1

Pythons range function

Python has a function that generates numbers, the range function. This function creates a list of numbers.

The range function is often used in a for loop, to repeat a certain number of times. You can see it used for creating a list of numbers too, writing down every number manually is just to cumbersome.

Range list examples

If the range function has only one parameter, it will count from zero to the end.

range(end)

In Python 3 you must parse it to a list. Thus making it a simple numeric list. We store the list in variable l, which we then use to output.

>>> l = list(range(5))
>>> print(l)
[0, 1, 2, 3, 4]
>>> 

The function permits definition of starting and step size. To start at 5 and have a step size of 2:

>>> l = list(range(5,50,2))
>>> print(l)
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
>>> 

Range loop example

For loops are one way of repeating code (iteration). That means, you don't have to rewrite the same instructions over and over but just can "jump back" or repeat lines.

For use in a for loop you don't need to parse to a list,

>>> for i in range(0,6):
...     print(i)
... 
0
1
2
3
4
5
>>> 

In the for loop you can use step size and starting value. In this case starting at 1 with a step size of 3.

>>> for i in range(1,30,3):
...     print(i)
... 
1
4
7
10
13
16
19
22
25
28
>>>

Related links:

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay