Bootstrap demo
Python Range Function

Table of Contents

1. Introduction to Range Function

The range() function is one of the most fundamental and frequently used built-in functions in Python. It generates a sequence of numbers and is primarily used in loops, list comprehensions, and anywhere you need a sequence of integers.

🔑 Key Points:

2. Definition and Purpose

The range() function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before a specified number. It doesn't actually create a list of numbers in memory but generates them on-demand, making it memory efficient.

📝 Important: In Python 3, range() returns a range object, not a list. In Python 2, range() returned a list, and xrange() returned an iterator (similar to Python 3's range).

3. Syntax and Parameters

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

start (optional)

Type: Integer

Default: 0

Description: The starting number of the sequence. If omitted, starts from 0.

stop (required)

Type: Integer

Default: None

Description: The ending number of the sequence (exclusive). The sequence stops before this number.

step (optional)

Type: Integer

Default: 1

Description: The increment between each number in the sequence. Can be negative.

4. Basic Usage Examples

🚀 Quick Start Examples

# Basic range usage
for i in range( >5):
     print(i)

# Converting range to list to see all values
numbers = list( range( >5))
print(numbers)

# Using range in list comprehension
squares = [x** >2 for x in range( >5)]
print(squares)
0
1
2
3
4
[0, 1, 2, 3, 4]
[0, 1, 4, 9, 16]

5. Single Parameter Range

When you provide only one argument to range(), it represents the stop value. The sequence starts from 0 and goes up to (but not including) the stop value.

Function Call Generated Sequence Description
range(0) Empty sequence No numbers generated
range(1) [0] Single number: 0
range(5) [0, 1, 2, 3, 4] Numbers from 0 to 4
range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Numbers from 0 to 9

Single Parameter Examples

# Counting from 0 to n-1
print( "Counting to 3:")
for i in range( >3):
     print( f"Count: {i}")

# Creating a list of indices
my_list = [ 'apple', 'banana', 'cherry']
for index in range( len(my_list)):
     print( f"Index {index}: {my_list[index]}")

# Empty range
empty_range = list( range( >0))
print( f"Empty range: {empty_range}")

6. Two Parameters Range

When you provide two arguments, the first is the start value and the second is the stop value. The sequence begins at start and goes up to (but not including) stop.

Function Call Generated Sequence Description
range(1, 5) [1, 2, 3, 4] From 1 to 4
range(5, 10) [5, 6, 7, 8, 9] From 5 to 9
range(-3, 3) [-3, -2, -1, 0, 1, 2] From -3 to 2
range(10, 5) Empty sequence Start > Stop with positive step

Two Parameters Examples

# Custom start and stop
print( "Numbers from 3 to 7:")
for num in range( >3, >8):
     print(num)

# Working with negative numbers
negative_range = list( range(- >5, >1))
print( f"Negative to positive: {negative_range}")

# Year range example
print( "Years from 2020 to 2024:")
for year in range( >2020, >2025):
     print(year)

7. Three Parameters Range

When you provide three arguments, you specify start, stop, and step. The step determines the increment between consecutive numbers.

Function Call Generated Sequence Description
range(0, 10, 2) [0, 2, 4, 6, 8] Even numbers from 0 to 8
range(1, 10, 2) [1, 3, 5, 7, 9] Odd numbers from 1 to 9
range(0, 20, 5) [0, 5, 10, 15] Multiples of 5 up to 15
range(2, 16, 3) [2, 5, 8, 11, 14] Step of 3 from 2 to 14

Three Parameters Examples

# Even numbers
even_numbers = list( range( >0, >11, >2))
print( f"Even numbers: {even_numbers}")

# Odd numbers
odd_numbers = list( range( >1, >11, >2))
print( f"Odd numbers: {odd_numbers}")

# Multiples of 3
print( "Multiples of 3 up to 30:")
for multiple in range( >3, >31, >3):
     print(multiple, end= " ")
print() # New line

# Large step size
big_steps = list( range( >0, >100, >25))
print( f"Steps of 25: {big_steps}")

8. Negative Step Values

You can use negative step values to create descending sequences. When using negative steps, the start value should be greater than the stop value.

Function Call Generated Sequence Description
range(10, 0, -1) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] Countdown from 10 to 1
range(5, -1, -1) [5, 4, 3, 2, 1, 0] From 5 down to 0
range(20, 0, -5) [20, 15, 10, 5] Descending by 5
range(0, 10, -1) Empty sequence Invalid: start < stop with negative step

Negative Step Examples

# Countdown
print( "Countdown:")
for i in range( >5, >0, - >1):
     print(i)
print( "Blast off!")

# Reverse list indices
my_list = [ 'a', 'b', 'c', 'd', 'e']
print( "Reverse iteration:")
for i in range( len(my_list)- >1, - >1, - >1):
     print( f"Index {i}: {my_list[i]}")

# Even numbers in reverse
reverse_evens = list( range( >10, - >1, - >2))
print( f"Even numbers in reverse: {reverse_evens}")

9. Range Object Properties

The range object has several useful properties and methods that make it versatile for different programming scenarios.

Range Object Properties

# Creating a range object
r = range( >2, >20, >3)

# Accessing properties
print( f"Start: {r.start}")
print( f"Stop: {r.stop}")
print( f"Step: {r.step}")

# Length of range
print( f"Length: {len(r)}")

# Check membership
print( f"5 in range: {5 in r}")
print( f"8 in range: {8 in r}")

# Indexing
print( f"First element: {r[0]}")
print( f"Last element: {r[-1]}")

# Slicing
print( f"First 3 elements: {list(r[:3])}")

10. Converting Range to Lists

While range objects are memory efficient, sometimes you need to convert them to lists for certain operations.

Method Code Result Use Case
Direct conversion list(range(5)) [0, 1, 2, 3, 4] Simple conversion
List comprehension [x for x in range(5)] [0, 1, 2, 3, 4] With transformations
Unpacking [*range(5)] [0, 1, 2, 3, 4] Quick unpacking

Conversion Examples

# Basic conversion
range_obj = range( >1, >6)
list_from_range = list(range_obj)
print( f"List from range: {list_from_range}")

# List comprehension with transformation
squares = [x** >2 for x in range( >1, >6)]
print( f"Squares: {squares}")

# Unpacking operator
unpacked = [* range( >5, >10)]
print( f"Unpacked: {unpacked}")

# Converting to other types
range_tuple = tuple( range( >3))
range_set = set( range( >5))
print( f"Tuple: {range_tuple}")
print( f"Set: {range_set}")

11. Memory Efficiency

One of the key advantages of range objects is their memory efficiency. They don't store all values in memory but generate them on demand.

🧠 Memory Comparison:

Memory Efficiency Demonstration

import sys

# Compare memory usage
range_obj = range( >1000000)
list_obj = list( range( >1000000))

print( f"Range object size: {sys.getsizeof(range_obj)} bytes")
print( f"List object size: {sys.getsizeof(list_obj)} bytes")

# Range is still iterable
print( "First 10 elements from range:")
for i, value in enumerate(range_obj):
     if i >= >10:
         break
     print(value, end= " ")

12. Practical Examples

Example 1: Multiplication Table

def multiplication_table(number, limit= >10):
     """Generate multiplication table for a number"""
     print( f"Multiplication table for {number}:")
     for i in range( >1, limit + >1):
        result = number * i
         print( f"{number} × {i} = {result}")

# Generate table for 7
multiplication_table( >7, >5)

Example 2: Password Generator

import random
import string

def generate_password(length= >8):
     """Generate a random password"""
    characters = string.ascii_letters + string.digits + "!@#$%^&*"
    password = ""
    
     for _ in range(length):
        password += random.choice(characters)
    
     return password

# Generate 5 passwords
print( "Generated passwords:")
for i in range( >5):
    password = generate_password( >12)
     print( f"Password {i+1}: {password}")

Example 3: Grade Calculator

def calculate_grades(scores):
     """Calculate letter grades for a list of scores"""
    grades = []
    
     for i in range( len(scores)):
        score = scores[i]
         if score >= >90:
            grade = 'A'
         elif score >= >80:
            grade = 'B'
         elif score >= >70:
            grade = 'C'
         elif score >= >60:
            grade = 'D'
         else:
            grade = 'F'
        
        grades.append(grade)
         print( f"Student {i+1}: {score}% = {grade}")
    
     return grades

# Example scores
student_scores = [ >95, >87, >76, >92, >68, >84]
final_grades = calculate_grades(student_scores)

13. Common Usage Patterns

Pattern 1: Enumerate Alternative

# Using range instead of enumerate
fruits = [ 'apple', 'banana', 'cherry', 'date']

# Method 1: Using enumerate (preferred)
print( "Using enumerate:")
for index, fruit in enumerate(fruits):
     print( f"{index}: {fruit}")

# Method 2: Using range
print( "Using range:")
for i in range( len(fruits)):
     print( f"{i}: {fruits[i]}")

Pattern 2: Matrix Operations

# Creating and working with 2D matrices
rows, cols = >3, >4

# Create matrix using nested loops with range
matrix = []
for i in range(rows):
    row = []
     for j in range(cols):
        row.append(i * cols + j + >1)
    matrix.append(row)

# Print matrix
print( "Matrix:")
for i in range(rows):
     for j in range(cols):
         print( f"{matrix[i][j]:3}", end= " ")
     print() # New line after each row

Pattern 3: Batch Processing

def process_in_batches(data, batch_size):
     """Process data in batches"""
     for i in range( >0, len(data), batch_size):
        batch = data[i:i + batch_size]
         print( f"Processing batch {i//batch_size + 1}: {batch}")
         # Process batch here

# Example usage
large_dataset = list( range( >1, >21)) # Numbers 1-20
process_in_batches(large_dataset, >5)

14. Best Practices

✅ Do's:

❌ Don'ts:

Best Practice Examples

# ✅ Good: Using enumerate for index and value
items = [ 'apple', 'banana', 'cherry']
for index, item in enumerate(items):
     print( f"{index}: {item}")

# ❌ Less ideal: Using range(len())
for i in range( len(items)):
     print( f"{i}: {items[i]}")

# ✅ Good: Direct iteration when index not needed
for item in items:
     print(item)

# ✅ Good: Using range for mathematical sequences
fibonacci = [ >0, >1]
for i in range( >2, >10):
    fibonacci.append(fibonacci[i- >1] + fibonacci[i- >2])
print( f"Fibonacci: {fibonacci}")

15. Common Errors and Solutions

Error Cause Solution Example
ValueError: step argument must not be zero Using step=0 Use non-zero step value range(0, 10, 1) instead of range(0, 10, 0)
Empty range start ≥ stop with positive step Check start/stop values or use negative step range(10, 0, -1) for countdown
TypeError: 'range' object is not subscriptable Trying to slice range in Python 2 Convert to list first or use Python 3 list(range(10))[2:5]
OverflowError Range values too large Use smaller values or different approach Consider itertools for very large ranges

Error Handling Examples

# Handling potential errors
def safe_range(start, stop, step= >1):
     """Create a range with error checking"""
     try:
         if step == >0:
             raise ValueError( "Step cannot be zero")
        
        r = range(start, stop, step)
        
         if len(r) == >0:
             print( f"Warning: Empty range({start}, {stop}, {step})")
        
         return r
    
     except ValueError as e:
         print( f"Error: {e}")
         return range( >0) # Return empty range

# Test error handling
print( "Testing safe_range:")
r1 = safe_range( >1, >5) # Valid
r2 = safe_range( >5, >1) # Empty range warning
r3 = safe_range(