Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create list of numbers with given range in Python
Python provides several built-in functions and libraries to generate sequences of numbers within a specified range. This article explores different approaches using range(), random.randrange(), and NumPy's arange() function.
Using range() Function
The range() function generates a sequence of numbers starting from 0 by default, incrementing by 1, and ending before a specified number. You can customize the start, end, and step values to meet your requirements.
Example
def generate_numbers(start, end, step):
return list(range(start, end, step))
# Generate numbers from -3 to 6 with step 2
start, end, step = -3, 6, 2
numbers = generate_numbers(start, end, step)
print(numbers)
[-3, -1, 1, 3, 5]
Using random.randrange()
The random.randrange() function returns a single random number from the specified range. Unlike range(), this method generates only one random value within the given parameters.
Example
import random
def get_random_number(start, end, step):
return random.randrange(start, end, step)
# Get a random number from 3 to 16 with step 2
start, end, step = 3, 16, 2
random_num = get_random_number(start, end, step)
print(random_num)
7
Using NumPy arange()
NumPy's arange() function provides similar functionality to range() but returns a NumPy array instead of a Python list. It's particularly useful for numerical computations and scientific applications.
Example
import numpy as np
def generate_array(start, end, step):
return np.arange(start, end, step)
# Generate array from 3 to 16 with step 2
start, end, step = 3, 16, 2
numbers_array = generate_array(start, end, step)
print(numbers_array)
[ 3 5 7 9 11 13 15]
Comparison
| Method | Return Type | Use Case |
|---|---|---|
range() |
Python list | General-purpose number sequences |
random.randrange() |
Single integer | Random number selection |
np.arange() |
NumPy array | Numerical computations |
Conclusion
Use range() for creating lists of sequential numbers, random.randrange() for selecting random values from a range, and np.arange() for numerical operations requiring NumPy arrays. Each method serves different purposes in Python programming.
