πŸ“ Python range() Function β€” Generating Number Sequences Easily

Introduction 🌟

The range() function is used to generate a sequence of numbers. It is most commonly used inside for loops, but can also be converted into lists, iterated manually, or used in logic conditions.

Note

πŸ’‘ range() does NOT create a list in memory β€” it creates a lightweight sequence object, making it memory efficient.

1. Basic Syntax 🧱

range(stop)range(start, stop)range(start, stop, step)

2. range(stop) β€” Starts From 0 πŸ”’

range_stop.py

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

βœ”οΈ Outputs: 0, 1, 2, 3, 4
βœ”οΈ Stops before 5

3. range(start, stop) β€” Custom Start πŸ“

range_start_stop.py

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

βœ”οΈ Outputs: 2, 3, 4, 5
βœ”οΈ Stop value is *exclusive*

4. range(start, stop, step) β€” With Step Size πŸšΆβ€β™‚οΈ

range_step.py

for i in range(1, 10, 2):
    print(i)

βœ”οΈ Outputs odd numbers: 1, 3, 5, 7, 9

5. Negative Step β€” Counting Backwards ⬇️

range_negative_step.py

for i in range(10, 0, -1):
    print(i)

βœ”οΈ Countdown from 10 to 1
βœ”οΈ Stop value (0) is excluded

6. Converting Range to List πŸ“š

range_to_list.py

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

Note

βœ”οΈ Useful when you need all values stored at once.

7. Using Range in While Loop πŸ”„

range_in_while.py

i = 0
nums = range(5)

while i < len(nums):
    print(nums[i])
    i += 1

8. Range With Conditions 🧠

range_condition.py

for i in range(1, 20):
    if i % 5 == 0:
        print(i)

βœ”οΈ Prints multiples of 5 between 1 and 19.

9. Using Range in Nested Loops πŸͺœ

nested_range.py

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

10. Skipping Values With Step πŸƒβ€β™‚οΈ

skip_values.py

for i in range(0, 20, 3):
    print(i)

βœ”οΈ Outputs: 0, 3, 6, 9, 12, 15, 18

11. Using Range for Indexing πŸ“Œ

indexing_with_range.py

fruits = ["apple", "banana", "mango"]

for i in range(len(fruits)):
    print(i, fruits[i])

12. range() in Reverse Using reversed() πŸ”„

range_reversed.py

for i in reversed(range(1, 6)):
    print(i)

13. Check If Value Exists in Range πŸ”

range_membership.py

print(5 in range(1, 10))   # True
print(10 in range(1, 10))  # False

14. Range Efficiency πŸš€

range() is extremely efficient because it generates values on demand rather than storing them in memory.

Note

🧠 Use range() for large sequences to avoid memory issues.

15. Real-World Example 🌍

real_world_example.py

for attempt in range(1, 4):
    pin = input("Enter PIN: ")
    if pin == "1234":
        print("Access granted")
        break
    print("Wrong PIN, attempt", attempt)

Conclusion πŸŽ‰

>>β€œrange() is the backbone of Python loops β€” simple, powerful, and memory efficient.” ✨

You now fully understand the range() function in Python! Want the next topic? Try Pass Statement, Functions, Parameters, or List Comprehensions. Just tell me! 😊