Python range() Function

for number in range(0,6):
print(number)
0
1
2
3
4
5
for number in range(0, 60, 10):
print(number)
0
10
20
30
40
50
for number in range(5,0, -1):
print(number)
5
4
3
2
1

Python range() Function in Detail

for number in range(some_number):
# Do something
1. range(end)
2. range(start, end)
3. range(start, end, stepsize)

1. range(end)—Only Specify the End Value for a Range

nums = range(6)
range(0, 6)
nums = list(range(6))
print(nums)
[0, 1, 2, 3, 4, 5]

2. range(start, end)—Specify Both Start and End Values for a Range

range(-2,3)
rng = range(-2, 3)
nums_list = list(rng)
print(nums_list)
[-2, -1, 0, 1, 2]

3. range(start, end, stepsize)—Range with a Custom Step Size

rng = range(-20, 30, 10)
nums_list = list(rng)
print(nums_list)
[-20, -10, 0, 10, 20]

Python range() Function Usage Examples

Use range() with a For Loop

for number in range(0, 6):
print(number)
0
1
2
3
4
5

Increment with Python’s range() Function

for num in range(0, 4):
print(num)
0
1
2
3

Decrement with Python’s range() Function

for num in range(4, 0, -1):
print(num)
4
3
2
1
for num in reversed(range(1, 5)):
print(num)
4
3
2
1

Ignore the Index When Looping

for i in range(5):
print("Hello!")
Hello!
Hello!
Hello!
Hello!
Hello!
for _ in range(5):
print("Hello!")
Hello!
Hello!
Hello!
Hello!
Hello!

Do Not Use range() Function Blindly

queue = ["Jack", "Ann", "Sofie"]for i in range(len(queue)):
name = queue[i]
print(f"{name} is at {i+1}. position")
Jack is at 1. position
Ann is at 2. position
Sofie is at 3. position
queue = ["Jack", "Ann", "Sofie"]

for pos, name in enumerate(queue):
print(f"{name} is at {pos + 1}. position")
Jack is at 1. position
Ann is at 2. position
Sofie is at 3. position

Conclusion

  • Numbers in increasing order.
  • Numbers in decreasing order.
  • Numbers with a custom step size.

Further Reading

References

--

--

--

I’m a tech expert, entrepreneur, and software engineer from Finland. I write about programming, tech, and science. Visit my blog at www.codingem.com.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

My Favorite Free Courses to Learn Python In-Depth

Building APIs With Python

You Either love it or you haven’t used it, yet.

How Unity DOTS paves the way for the future of Game Development

Why do we need to write good code?

Kubernetes, Plug-ins and TMUX

AWS SDK 1.x to 2.x migration and upgrade — learnings and takeaways

QuickBooks POS: Window Switcher

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Artturi Jalli

Artturi Jalli

I’m a tech expert, entrepreneur, and software engineer from Finland. I write about programming, tech, and science. Visit my blog at www.codingem.com.

More from Medium

Learning Python - Modules and Packages

Python for loop

Variables in Python

Namespaces in Python