In PY3, range is an object that can generate a sequence of numbers; it is not the actual sequence. You may need to brush up on some basic Python reading, paying attention to things like lists and generators, and their differences.

In [359]: x = range(3)                                                                                 
In [360]: x                                                                                            
Out[360]: range(0, 3)

We have use something like list or a list comprehension to actually create those numbers:

In [361]: list(x)                                                                                      
Out[361]: [0, 1, 2]
In [362]: [i for i in x]                                                                        
Out[362]: [0, 1, 2]

A range is often used in a for i in range(3): print(i) kind of loop.

arange is a numpy function that produces a numpy array:

In [363]: arr = np.arange(3)                                                                           
In [364]: arr                                                                                          
Out[364]: array([0, 1, 2])

We can iterate on such an array, but it is slower than [362]:

In [365]: [i for i in arr]                                                                             
Out[365]: [0, 1, 2]

But for doing things math, the array is much better:

In [366]: arr * 10                                                                                     
Out[366]: array([ 0, 10, 20])

The array can also be created from the list [361] (and for compatibility with earlier Py2 usage from the range itself):

In [376]: np.array(list(x))     # np.array(x)                                                                        
Out[376]: array([0, 1, 2])

But this is slower than using arange directly (that's an implementation detail).

Despite the similarity in names, these shouldn't be seen as simple alternatives. Use range in basic Python constructs such as for loop and comprehension. Use arange when you need an array.

An important innovation in Python (compared to earlier languages) is that we could iterate directly on a list. We didn't have to step through indices. And if we needed indices along with with values we could use enumerate:

In [378]: alist = ['a','b','c']                                                                        
In [379]: for i in range(3): print(alist[i])   # index iteration                                                        
a
b
c
In [380]: for v in alist: print(v)    # iterate on list directly                                       
a
b
c
In [381]: for i,v in enumerate(alist): print(i,v)    #  index and values                                                  
0 a
1 b
2 c

Thus you might not see range used that much in basic Python code.

Answer from hpaulj on Stack Overflow
Top answer
1 of 3
4

In PY3, range is an object that can generate a sequence of numbers; it is not the actual sequence. You may need to brush up on some basic Python reading, paying attention to things like lists and generators, and their differences.

In [359]: x = range(3)                                                                                 
In [360]: x                                                                                            
Out[360]: range(0, 3)

We have use something like list or a list comprehension to actually create those numbers:

In [361]: list(x)                                                                                      
Out[361]: [0, 1, 2]
In [362]: [i for i in x]                                                                        
Out[362]: [0, 1, 2]

A range is often used in a for i in range(3): print(i) kind of loop.

arange is a numpy function that produces a numpy array:

In [363]: arr = np.arange(3)                                                                           
In [364]: arr                                                                                          
Out[364]: array([0, 1, 2])

We can iterate on such an array, but it is slower than [362]:

In [365]: [i for i in arr]                                                                             
Out[365]: [0, 1, 2]

But for doing things math, the array is much better:

In [366]: arr * 10                                                                                     
Out[366]: array([ 0, 10, 20])

The array can also be created from the list [361] (and for compatibility with earlier Py2 usage from the range itself):

In [376]: np.array(list(x))     # np.array(x)                                                                        
Out[376]: array([0, 1, 2])

But this is slower than using arange directly (that's an implementation detail).

Despite the similarity in names, these shouldn't be seen as simple alternatives. Use range in basic Python constructs such as for loop and comprehension. Use arange when you need an array.

An important innovation in Python (compared to earlier languages) is that we could iterate directly on a list. We didn't have to step through indices. And if we needed indices along with with values we could use enumerate:

In [378]: alist = ['a','b','c']                                                                        
In [379]: for i in range(3): print(alist[i])   # index iteration                                                        
a
b
c
In [380]: for v in alist: print(v)    # iterate on list directly                                       
a
b
c
In [381]: for i,v in enumerate(alist): print(i,v)    #  index and values                                                  
0 a
1 b
2 c

Thus you might not see range used that much in basic Python code.

2 of 3
1

the range type constructor creates range objects, which represent sequences of integers with a start, stop, and step in a space efficient manner, calculating the values on the fly.

np.arange function returns a numpy.ndarray object, which is essentially a wrapper around a primitive array. This is a fast and relatively compact representation, compared to if you created a python list, so list(range(N)), but range objects are more space efficient, and indeed, take constant space, so for all practical purposes, range(a) is the same size as range(b) for any integers a, b

As an aside, you should take care interpreting the results of sys.getsizeof, you must understand what it is doing. So do not naively compare the size of Python lists and numpy.ndarray, for example.

Perhaps whatever you read was referring to Python 2, where range returned a list. List objects do require more space than numpy.ndarray objects, generally.

๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ generated โ€บ numpy.arange.html
numpy.arange โ€” NumPy v2.5.dev0 Manual
arange(start, stop, step) Values are generated within the half-open interval [start, stop), with spacing between values given by step. For integer arguments the function is roughly equivalent to the Python built-in range, but returns an ndarray rather than a range instance.
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ range vs arange: choosing the right tool for your python code
Range vs Arange: Choosing the Right Tool for Your Python Code - Pierian Training
April 28, 2023 - However, if you need more flexibility with your sequence generation, such as generating non-integer values or specifying an inclusive endpoint, then using `arange()` may be more appropriate.
Top answer
1 of 3
95

For large arrays, a vectorised numpy operation is the fastest. If you must loop, prefer xrange/range and avoid using np.arange.

In numpy you should use combinations of vectorized calculations, ufuncs and indexing to solve your problems as it runs at C speed. Looping over numpy arrays is inefficient compared to this.

(Something like the worst thing you could do would be to iterate over the array with an index created with range or np.arange as the first sentence in your question suggests, but I'm not sure if you really mean that.)

import numpy as np
import sys

sys.version
# out: '2.7.3rc2 (default, Mar 22 2012, 04:35:15) \n[GCC 4.6.3]'
np.version.version
# out: '1.6.2'

size = int(1E6)

%timeit for x in range(size): x ** 2
# out: 10 loops, best of 3: 136 ms per loop

%timeit for x in xrange(size): x ** 2
# out: 10 loops, best of 3: 88.9 ms per loop

# avoid this
%timeit for x in np.arange(size): x ** 2
#out: 1 loops, best of 3: 1.16 s per loop

# use this
%timeit np.arange(size) ** 2
#out: 100 loops, best of 3: 19.5 ms per loop

So for this case numpy is 4 times faster than using xrange if you do it right. Depending on your problem numpy can be much faster than a 4 or 5 times speed up.

The answers to this question explain some more advantages of using numpy arrays instead of python lists for large data sets.

2 of 3
13

First of all, as written by @bmu, you should use combinations of vectorized calculations, ufuncs and indexing. There are indeed some cases where explicit looping is required, but those are really rare.

If explicit loop is needed, with python 2.6 and 2.7, you should use xrange (see below). From what you say, in Python 3, range is the same as xrange (returns a generator). So maybe range is as good for you.

Now, you should try it yourself (using timeit: - here the ipython "magic function"):

%timeit for i in range(1000000): pass
[out] 10 loops, best of 3: 63.6 ms per loop

%timeit for i in np.arange(1000000): pass
[out] 10 loops, best of 3: 158 ms per loop

%timeit for i in xrange(1000000): pass
[out] 10 loops, best of 3: 23.4 ms per loop

Again, as mentioned above, most of the time it is possible to use numpy vector/array formula (or ufunc etc...) which run a c speed: much faster. This is what we could call "vector programming". It makes program easier to implement than C (and more readable) but almost as fast in the end.

๐ŸŒ
Plain English
python.plainenglish.io โ€บ range-python-vs-arange-numpy-8d4c0f8d6a30
range (Python) vs. arange (NumPy) | Python in Plain English
August 10, 2024 - In this example, range is perfect for generating the indices needed to access each item in the list. If youโ€™re working on a numerical computation where you need an array of floating-point numbers, arange is the tool to use: import numpy as np # Generate an array from 0 to 2ฯ€ with a step ...
Find elsewhere
๐ŸŒ
Real Python
realpython.com โ€บ how-to-use-numpy-arange
NumPy arange(): How to Use np.arange() โ€“ Real Python
July 31, 2023 - Its most important type is an array type called ndarray. NumPy offers a lot of array creation routines for different circumstances. arange() is one such function based on numerical ranges. Itโ€™s often referred to as np.arange() because np is a widely used abbreviation for NumPy.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.arange.html
numpy.arange โ€” NumPy v2.4 Manual
>>> np.arange(0, 5, 0.5, dtype=int) ... 6, 7, 8]) In such cases, the use of numpy.linspace should be preferred. The built-in range generates Python built-in integers that have arbitrary size, while numpy.arange produces numpy.int32 or numpy.int64 numbers....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ numpy-arrange-in-python
numpy.arange() in Python - GeeksforGeeks
February 14, 2026 - It is similar to Python's built-in range() function but returns a NumPy array instead of a list. Example: This example creates a NumPy array containing values from 5 to 9 using numpy.arange(). ... Return Type: array of evenly spaced values.
๐ŸŒ
Quora
quora.com โ€บ What-is-difference-between-arange-and-linspace-functions-of-NumPy
What is difference between arange() and linspace() functions of NumPy? - Quora
Answer (1 of 6): arange() :- Arange() return values with in a range which has a space between values. Syntax :- numpy.arange(start, stop, step, dtype=None, *, like=None) Example :โ€” linspace() :- Return set of samples with in a given interval. Syntax :- linspace(start, stop, num=50, endpoin...
๐ŸŒ
H2K Infosys
h2kinfosys.com โ€บ blog โ€บ mastering range of numbers in array with numpy: arange & linspace simplified
Mastering Range of Numbers in Array with Numpy: arange & linspace Simplified
October 31, 2025 - More precise for floating-point ranges. ... Slightly slower due to more complex calculations. Less intuitive for sequences with a specific step size. Scenario: Creating a sequence of integers for indexing or iteration. python # Creating indices ...
๐ŸŒ
STechies
stechies.com โ€บ range-vs-arangein-python
range() vs. arange() in Python
import numpy as np x = np.arange(1, 11, 2) print(x) Output: [1 3 5 7 9] Let us now check the difference between range() and arange(). range() vs. arange(): Although, both of them do the same type of consecutive number generation, there exist certain differences between both of them.
๐ŸŒ
The Python Coding Stack
thepythoncodingstack.com โ€บ p โ€บ difference-between-numpy-arange-and-linspace
What's The Difference Between NumPy's `arange()` and `linspace()` (A NumPy for Numpties article)
July 18, 2024 - NumPy's arange() returns a NumPy 'ndarray'. Like most number ranges in Python, the start value is included, but the stop value isn't. Therefore, Arav uses 151 as the stop value to make sure 150 is included in the cone positions.
๐ŸŒ
DeepLearning.AI
community.deeplearning.ai โ€บ course q&a โ€บ machine learning specialization โ€บ supervised ml: regression and classification
What's the purpose of a.shape and np.arange? - Supervised ML: Regression and Classification - DeepLearning.AI
April 17, 2024 - Week2: optional lab Python,Numpy & vectorization I am sorry. I am beginner. So I have basic questions at time. What is the purpose of a.shape? what is this .shape used for? Also, why do we write np.arange? when do we need it? In the following code in the screenshot, a[2].shape: (). Why does ...
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ built-in-range-or-numpy-arange-which-is-more-efficient.aspx
Python - Built-in range() or numpy.arange(): which is more efficient?
If we want to loop, we should prefer xrange()/range() and avoid using numpy.arange(). In numpy we should use combinations of vectorized calculations, ufuncs and indexing to solve our problems as it runs at C speed. Looping over numpy arrays is inefficient compared to this. ... import timeit # For Loop using range print("Time for range function:\n",timeit.Timer('for i in range(1):pass').timeit(),"\n") import numpy as np # For Loop using np.arange print("Time for range function:\n",timeit.Timer('for i in np.arange(1):pass', globals=dict(np=np)).timeit(),"\n")
๐ŸŒ
DataCamp
datacamp.com โ€บ doc โ€บ numpy โ€บ arange
NumPy arange()
`numpy.arange()` is used to create a sequence of numbers in a specified range. It can define the start, stop (non-inclusive), and step size for the array values. ... This creates an array with values from 0 to 4. import numpy as np array = np.arange(2, 10, 2) print(array)
๐ŸŒ
Aaltoscicomp
aaltoscicomp.github.io โ€บ python-for-scicomp โ€บ numpy
NumPy โ€” Python for Scientific Computing documentation
You can select ranges where a condition is true. Clever and efficient use of these operations is a key to NumPyโ€™s speed: you should try to cleverly use these selectors (written in C) to extract data to be used with other NumPy functions written in C or Fortran. This will give you the benefits of Python with most of the speed of C. a = np.arange...
๐ŸŒ
Statology
statology.org โ€บ home โ€บ numpy: the difference between np.linspace and np.arange
NumPy: The Difference Between np.linspace and np.arange
July 21, 2022 - This tutorial explains the difference between the NumPy functions linspace() and arange(), including examples.
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ python
Data Analysis with Python: Numpy Operations - Python - The freeCodeCamp Forum
June 14, 2021 - It says I chose the incorrect answer, for the exercise before moving to the next lesson. However, I ran the code separately to make sure I was wrong, but it turns out I was right. โ€œWhat is the value of a after you run the following code?โ€ a = np.arange(5) a + 20 [20, 21, 22, 24, 24] [0, 1, 2, 3, 4] [25, 26, 27, 28, 29] The answer that it accepts is the second, [0, 1, 2, 3, 4]. This is cool but the code has a + 20, which I automatically read as โ€œarray([20, 21, 22, 23, 24])โ€. I tested it b...