MyInternships.in

Python Control Flow

Python range() Function

range() generates a sequence of numbers on demand, and is most often used to control how many times a for loop runs.


range(stop) — One Argument

When you pass a single number to range(), it produces numbers starting at 0 up to (but not including) that number. This makes range(5) produce 0, 1, 2, 3, 4 — five values in total.

range with one argument
Python
for i in range(5):
    print(i)

range(start, stop) — Two Arguments

Passing two numbers sets a custom starting point. range(start, stop) counts from start up to, but not including, stop.

range with start and stop
Python
for i in range(2, 7):
    print(i)

range(start, stop, step) — Three Arguments

A third argument sets the step size, letting you count by twos, count backwards, or skip values. A negative step counts downward.

range with a step
Python
for i in range(10, 0, -2):
    print(i)
CallValues produced
range(5)0, 1, 2, 3, 4
range(2, 6)2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(5, 0, -1)5, 4, 3, 2, 1

range() Inside for Loops

range() is most commonly used to repeat an action a fixed number of times, or to loop by index when you need position information alongside your data.

Using range for indexes
Python
names = ["Asha", "Rahul", "Meera"]
for i in range(len(names)):
    print(i, names[i])

Converting range() to a List

range() itself does not create a list — it produces a memory-efficient range object that generates numbers as needed. Wrap it in list() when you actually need a real list, for example to print it directly or pass it to functions expecting a list.

list(range())
Python
numbers = list(range(1, 6))
print(numbers)
Output
Output
[1, 2, 3, 4, 5]
💡

Prefer for item in names: over for i in range(len(names)): when you don’t actually need the index — it is simpler and more Pythonic. Reach for enumerate() when you need both.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships