How do I create a list with numbers between two values?
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:
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.
Floating like a butterfly? Sure!
For generating sequences involving floating-point increment, we tailor numpy's arange()
function to our needs.
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!
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.
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.
Optimizing with numpy
For very long bookshelves (a.k.a. libraries), nothing outperforms numpy's arange()
function due to its efficiency with large arrays.
Custom range generator
You can create your own generator to handle a specific sequence of numbers. Should we call it "book generator"?
Was this article helpful?