Python range(): Generate Sequences of Numbers

The range() function creates a sequence of numbers, commonly used for loops and iterating over numeric ranges efficiently. It’s useful for looping, indexing, and generating number sequences.

Example

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

Output:

0  
1  
2  
3  
4

Generates numbers from 0 to 4.

Syntax

range(start, stop, step)
  • start (optional) → The number to start from (default: 0).
  • stop → The number to stop at (excludes this value).
  • step (optional) → The increment (default: 1).

1. Using range() with One Argument (stop)

print(list(range(5)))
# Output: [0, 1, 2, 3, 4]

Starts from 0 and stops at 5 (excluding 5).

2. Using range() with Start and Stop

print(list(range(2, 6)))
# Output: [2, 3, 4, 5]

Starts from 2, stops before 6.

3. Using range() with Step

print(list(range(1, 10, 2)))
# Output: [1, 3, 5, 7, 9]

Generates odd numbers from 1 to 9.

4. Using Negative Step (Counting Down)

print(list(range(10, 0, -2)))
# Output: [10, 8, 6, 4, 2]

Counts backward from 10 to 2.

5. Iterating with range() in a Loop

for num in range(3):
    print(f"Item {num}")

Output:

Item 0  
Item 1  
Item 2

Loops 3 times (0 to 2).

6. Using range() to Generate Indices

words = ["Python", "is", "awesome"]
for i in range(len(words)):
    print(f"Word {i}: {words[i]}")

Loops over a list using indices.

7. Creating a List from range()

numbers = list(range(5))
print(numbers)
# Output: [0, 1, 2, 3, 4]

Convert range() to a list when needed.

Key Notes

  • Generates number sequences efficiently.
  • Default start is 0, default step is 1.
  • Use negative steps to count backward.
  • Commonly used in loops and indexing.

By using range(), you can loop efficiently, generate sequences, and manage numeric data with minimal memory usage. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top