Explain Codes LogoExplain Codes Logo

How do I create a list with numbers between two values?

python
list-comprehensions
numpy
range-function
Alex KataevbyAlex Kataev·Jan 18, 2025
TLDR

To generate a list of sequential numbers in Python, use the range() function inside a list comprehension: [num for num in range(start, end+1)]. For example, to create a list of numbers from 5 to 15:

numbers = [num for num in range(5, 16)] # "range" doesn't include 16, but we want 15, hence end+1

Producing the list: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]. Notice the use of end+1 to also include 15.

Dealing with range function boundaries

Python's range() function excludes the ending value from output list by default. Adding +1 to the end value ensures inclusivity in the list. But remember, this only holds for integer values.

inclusive_numbers = [num for num in range(1, 6)] # Well, isn't that "inclusive-ive"?

Floating like a butterfly? Sure!

For generating sequences involving floating-point increment, we tailor numpy's arange() function to our needs.

import numpy as np float_numbers = np.arange(0.0, 1.0, 0.1).tolist() # Float like a butterfly, don't sting like an int!

Remember, numpy's arange() function is more efficient and precise with large sequences and non-integer steps.

Making it complex but elegant

For generating ranges with complex increments or lists in reverse order, you cleverly use the power of list comprehensions with conditional logic!

# Whoa, reverse gear on! reverse_numbers = [num for num in range(15, 4, -1)] # 15...14...13...Beep beep beep... # Or even, uneven even_numbers = [num for num in range(5, 16) if num % 2 == 0] # Even Stephen would be proud!

Embrace the immutable’s mutable side

Python 3's range() returns an immutable sequence type. To convert this into a modifiable list, an explicit call to the 'list()' function is needed.

modifiable_numbers = list(range(5, 16)) # Range is hard as a rock. We prefer something a bit softer...a list!

In contrast, Python 2's range directly returns a list, no conversion needed. It's as if Python 2 already knew what you wanted!

Floating through numpy precision

When you need non-integer increments, say, floating-point books on your shelf, numpy's arange() soars.

float_books = np.arange(1.0, 2.0, 0.1).tolist() # Long shelf? Yes, please!

Optimizing with numpy

For very long bookshelves (a.k.a. libraries), nothing outperforms numpy's arange() function due to its efficiency with large arrays.

library_books = np.arange(1, 10000).tolist() # I always wanted my own library

Custom range generator

You can create your own generator to handle a specific sequence of numbers. Should we call it "book generator"?

def frange(start, stop, step): x = start while x < stop: yield x x += step tiny_step_books = list(frange(1.0, 2.0, 0.01)) # Books numbered in tiny steps, because why not!