In this video, I’m going to cover how to manipulate the ranges returned by NumPy’s
arange() function. As always, before you use this function you’re going to have to
import numpy, and it’s preferable to do it
as np, just as a convention.
The great thing about what
arange() returns is that it is—and I’m going to show you what it is—it has the type of a
ndarray is awesome because you can perform operations directly on the array and they’ll be performed element-wise on the elements of the array. So
2 ** x, the
ndarray(x), gives us an array which is each element in
2 raised to the power of that element. So
2 ** 0 is
2 ** 1 is
2, and so on. So it’s pretty cool.
You can also use NumPy functions. So if for example, I’m going to make a new
arange() here, and I’m going to start at
-10, I’m going to go to
10, and I’m going to go by
.5, just to increase the diversity of the numbers that we have in here. So here you go, starting at
-10 and going all the way up to
So you can do
np.abs(), which is the absolute value of
x. It gives you the absolute value of all these numbers. You can do
np.sin(), or even
cos() (cosine) or whatever, and get the sine values of all these. Pretty amazing, and it makes it really easy, for example, if you want to create a plot using a library like Matplotlib or something like that, because you can just generate all of these values and get their results super, super quickly and easily.
So one, two, three; one, two, three; one, two, three; so on. You can reshape it into essentially whatever you want. If you want to generate some kind of wacky, giant array with a really complex shape, but you know that the numbers in it form a kind of linear pattern, you can use
arange() and then
.reshape() just as needed.
Really simple and really, really cool, which is nice. NumPy is an awesome library in general, and I encourage you to check out NumPy as a whole. There are many Real Python tutorials on it, many worthwhile videos to watch and lessons to read. So go check that out, but in the meantime, feel free to use this
arange() function and reshaping it however you can.
Become a Member to join the conversation.