# Python NumPy Examples (array, random, arange)

This Python example page uses NumPy for numeric operations on arrays.**NumPy.** Python has serious limitations in numeric processing. External libraries like NumPy can improve performance—support for GPU acceleration is even possible.

**With methods** like np.array, we create arrays of numbers (of various types) in NumPy. Libraries like TensorFlow use NumPy. It is well-supported.

**An example.** To begin using NumPy, please install it from pip (a Python installer). Once installed, you can import "numpy" as "np."

**Np.array:** Here we create an array with np.array. A Python List is passed to the method. We then multiply the array by 2.

List**Python program that uses numpy**
import numpy as np*
# Create an array of 3 elements.
*array_one = __np.array__([5, 10, 15])
print(array_one)*
# An array can be multiplied by an int.
# ... This is an array broadcasting example.
*array_two = array_one * 2
print(array_two)
**Output**
[ 5 10 15]
[10 20 30]

**Random.** With NumPy we can generate an array of random values with a method call. We specify the size as an argument to random.normal.

**Here:** We generate a 1-dimensional array of 5 random float values. Some of the numbers are negative.

**Python program that gets random array**
import numpy as np*
# Create a 1-dimensional array of 5 random values.
*random_values = np.__random__.normal(size=[1, 5])
print(random_values)
**Output**
[[ 0.49786323 0.81794554 -0.63191935 0.25130401 0.80529426]]

**Arange.** With NumPy we can get an array based on ranges. The arange method receives 1, 2 or 3 arguments. This works similar to the slice syntax in Python itself.

**First argument:** This is the starting value for the range. So with 5, our range starts at the value 5.

**Second argument:** The exclusive end of the range—this value is not included in the range. With a value of 6, our range does not include 6.

**Third argument:** The step—this is how much each element in the resulting range is incremented. This is the same way Python slices work.

**Python program that uses arange**
import numpy as np*
# Get values using arange method.
# ... This is an exclusive bound.
*values = np.__arange__(*5*)
print(values)*
# Two arguments can be used.
# ... The second argument is an exclusive bound.
*values = np.__arange__(*3*, *6*)
print(values)*
# A step can be used.
*values = np.__arange__(*0*, *5*, *2*)
print(values)
**Output**
[0 1 2 3 4]
[3 4 5]
[0 2 4]

**Notes, broadcasting.** A powerful feature of NumPy is broadcasting. This allows you to multiply or add two arrays together, and have the elements themselves affected by their positions.

**Some notes.** NumPy is a powerful library. And its support in other libraries like TensorFlow make it a non-optional one (for certain use cases).

© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.