Array Creation Functions
Learn how to create NumPy arrays from sequences, generate numerical ranges, produce evenly spaced values, and choose the appropriate function for different data requirements.
1. Learning Objectives
After completing this lesson, you will be able to:
- Create arrays from Python lists and tuples.
- Use
np.asarray()to convert compatible input into an array. - Generate sequences using
np.arange(). - Create evenly spaced values using
np.linspace(). - Generate arrays using functions such as
np.full(). - Choose an appropriate array creation function for a problem.
- Recognize common mistakes involving range limits and step sizes.
2. Creating Arrays with np.array()
The np.array() function creates a NumPy array
from a sequence, such as a Python list or tuple. It is one
of the most commonly used ways to create arrays.
Example 1: Create an Array from a List
import numpy as np numbers = np.array([10, 20, 30, 40, 50]) print(numbers)
Output:
[10 20 30 40 50]
Example 2: Create an Array from a Tuple
values = np.array((5, 15, 25, 35)) print(values)
Output:
[ 5 15 25 35]
Example 3: Create a Two-Dimensional Array
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix)
Output:
[[1 2 3] [4 5 6]]
3. Understanding np.asarray()
The np.asarray() function converts compatible
input into a NumPy array. If the input is already an array
with a compatible data type, NumPy may return the same array
rather than creating a copy.
Example: Convert a List into an Array
import numpy as np data = [12, 24, 36, 48] array_data = np.asarray(data) print(array_data) print(type(array_data))
Output:
[12 24 36 48] <class 'numpy.ndarray'>
Both np.array() and np.asarray()
can create arrays from lists. Their copying behavior can
differ, so choose the function based on the requirements
of your program.
4. Generating Sequences with np.arange()
The np.arange() function generates values
separated by a specified step. It is useful when you need
a sequence with regular increments.
The general syntax is:
np.arange(start, stop, step)
| Parameter | Meaning |
|---|---|
start |
The starting value. Defaults to zero when omitted. |
stop |
The stopping boundary, which is excluded. |
step |
The increment between values. Defaults to one. |
Example 1: Specify a Start and Stop
numbers = np.arange(1, 6) print(numbers)
Output:
[1 2 3 4 5]
Example 2: Specify a Step
numbers = np.arange(2, 12, 2) print(numbers)
Output:
[ 2 4 6 8 10]
Example 3: Generate Values in Descending Order
numbers = np.arange(10, 0, -2) print(numbers)
Output:
[10 8 6 4 2]
np.arange(1, 6) produces values
from 1 through 5, not 6.
5. Understanding np.linspace()
The np.linspace() function generates a
specified number of evenly spaced values between a start
and an end value. By default, the endpoint is included.
The general syntax is:
np.linspace(start, stop, num=50, endpoint=True)
| Parameter | Meaning |
|---|---|
start |
The starting value. |
stop |
The ending value. |
num |
The number of values to generate. Defaults to 50. |
endpoint |
If true, includes the stop value. Defaults to true. |
Example 1: Generate Five Evenly Spaced Values
values = np.linspace(0, 10, num=5) print(values)
Output:
[ 0. 2.5 5. 7.5 10. ]
Example 2: Generate Three Values
values = np.linspace(10, 20, num=3) print(values)
Output:
[10. 15. 20.]
Example 3: Exclude the Endpoint
values = np.linspace(
0,
10,
num=5,
endpoint=False
)
print(values)
Output:
[0. 2. 4. 6. 8.]
np.linspace() when
the number of desired points matters more than choosing
a particular step size.
6. np.arange() vs np.linspace()
Both functions can generate numerical sequences, but they are designed around different inputs.
| Feature | np.arange() |
np.linspace() |
|---|---|---|
| Main control | Start, stop, and step. | Start, stop, and number of values. |
| Stop value | Excluded. | Included by default. |
| Number of values | Determined by the range and step. | Specified directly using num. |
| Common use | Integer sequences and regular increments. | Evenly spaced points over an interval. |
Compare the Functions
import numpy as np
sequence_a = np.arange(0, 11, 2)
sequence_b = np.linspace(0, 10, 6)
print("arange:", sequence_a)
print("linspace:", sequence_b)
Output:
arange: [ 0 2 4 6 8 10] linspace: [ 0. 2. 4. 6. 8. 10.]
The resulting values are evenly spaced in both examples, but one specifies a step while the other specifies the number of values.
7. Creating Arrays with np.full()
The np.full() function creates an array of
a specified shape and fills every element with the
supplied value.
Example 1: Create a One-Dimensional Array
filled = np.full(4, 7) print(filled)
Output:
[7 7 7 7]
Example 2: Create a Two-Dimensional Array
matrix = np.full((2, 3), 9) print(matrix)
Output:
[[9 9 9] [9 9 9]]
Example 3: Fill an Array with a Decimal Value
values = np.full(3, 2.5) print(values)
Output:
[2.5 2.5 2.5]
8. Using np.asarray() and np.array() in Practice
Consider a classroom exercise where Samadhan receives a list of marks and needs to process the values using NumPy.
Complete Program
import numpy as np
student_marks = [72, 84, 91, 67, 88]
marks_array = np.array(student_marks)
marks_view = np.asarray(student_marks)
print("Original List:", student_marks)
print("Array with np.array():", marks_array)
print("Array with np.asarray():", marks_view)
print("Total Marks:", np.sum(marks_array))
print("Average Marks:", np.mean(marks_array))
Output:
Original List: [72, 84, 91, 67, 88] Array with np.array(): [72 84 91 67 88] Array with np.asarray(): [72 84 91 67 88] Total Marks: 402 Average Marks: 80.4
Both functions create an array from the input list in this example. Their behavior can differ when the input is already an array, especially when copying or changing data types.
9. Common Mistakes and Best Practices
1. Expecting np.arange() to Include the Stop Value
The stop value is excluded. Adjust the stop boundary if you need a different sequence.
2. Confusing Step Size with Number of Values
np.arange() uses a step size, whereas
np.linspace() uses the requested number
of values.
3. Using a Zero Step
A zero step is invalid for np.arange().
Use a nonzero step with the appropriate direction.
4. Choosing a Step with Floating-Point Values Without Checking Results
Floating-point increments can produce results affected
by numerical precision. When an exact number of points
is required, consider using np.linspace().
5. Forgetting the Shape in np.full()
To create a two-dimensional array, specify a shape
such as (2, 3) rather than a single integer.
10. Classroom Practice Activity
Activity: Generate Numerical Sequences
At CIIT TRANING INSTITUTE, Pradnya is practicing NumPy array creation functions. Complete the following tasks in a Python file.
- Create an array containing the integers from 1 to 10.
- Generate even numbers from 2 to 20 using a step of 2.
- Generate six evenly spaced values between 0 and 30.
- Create a one-dimensional array containing five values of 4.
- Create a two-dimensional array with three rows and two columns, filled with 8.
- Compare the output of
np.arange()andnp.linspace(). - Calculate the total of one generated sequence.
Starter Code
import numpy as np
sequence = np.arange(1, 11)
even_numbers = np.arange(2, 21, 2)
spaced_values = np.linspace(0, 30, num=6)
filled_array = np.full(5, 4)
filled_matrix = np.full((3, 2), 8)
print("Sequence:", sequence)
print("Even Numbers:", even_numbers)
print("Spaced Values:", spaced_values)
print("Filled Array:", filled_array)
print("Filled Matrix:")
print(filled_matrix)
print("Sequence Total:", np.sum(sequence))
Review Questions
- What is the purpose of
np.array()? - What is the difference between
np.array()andnp.asarray()? - Explain the parameters of
np.arange(). - Why is the stop value excluded in
np.arange()? - What does the
numparameter control innp.linspace()? - How can you exclude the endpoint in
np.linspace()? - How do you create a 2D array filled with the value 5 using
np.full()? - When would you choose
np.linspace()instead ofnp.arange()?
Summary
In this lesson, you learned to create arrays from lists
and tuples using np.array() and
np.asarray().
You explored np.arange() for sequences with
a specified step, np.linspace() for a
specified number of evenly spaced values, and
np.full() for arrays filled with a chosen value.