We can create a NumPy array using various functions provided by the Python NumPy library. This package provides a multidimensional array object and various other required objects, routines, for efficient functionality.

Unlike Python lists, NumPy arrays support element-wise operations and are more memory-efficient, making them useful for mathematical computations.

Using numpy.array() Function

We can use the numpy.array() function to create an array by passing a Python list or tuple as an argument to the function. This function converts input data (like lists, tuples, etc.) into an ndarray (NumPy array). Following is the syntax:

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0, like=None)

Example: Creating a 1D NumPy Array

import numpy as np # Creating a 1D array from a list my_list = [1, 2, 3, 4, 5] my_array = np.array(my_list) print("1D Array:", my_array)

Output:

1D Array: [1 2 3 4 5]

Example: Creating a 2D NumPy Array

import numpy as np # Creating a 2D array from a list of lists arr = np.array([[1, 2, 3], [4, 5, 6]]) print("2D Array:\n", arr)

Output:

2D Array: [[1 2 3] [4 5 6]]

Using numpy.zeros() Function

We can also use the numpy.zeros() function for creating an array by specifying the desired shape of the array as a tuple or an integer. This function creates a NumPy array filled with zeros. It accepts the shape of the array as an argument and optionally the data type (dtype). By default, the data type is float64. Following is the syntax:

numpy.zeros(shape, dtype=float, order='C')

Example

import numpy as np # Creating an array of zeros arr = np.zeros(5) print(arr)

Output:

[0. 0. 0. 0. 0.]

Using numpy.ones() Function

On the other hand, the numpy.ones() function creates an array where all elements are set to 1. It accepts three main parameters: shape, dtype, and order.

numpy.ones(shape, dtype=None, order='C')
  • shape: defines the dimensions of the array.
  • dtype: specifies the desired data type of the array elements (default is float64).
  • order: determines the memory layout (C-style or Fortran-style).

Example: Creating 1D array of ones

import numpy as np arr = np.ones(3) print(arr)

Output:

[1. 1. 1.]

Example: Creating 2D array of ones

import numpy as np array_2d = np.ones((4, 3)) print(array_2d)

Output:

[[1. 1. 1.] [1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]

Example: Creating a Fortran-ordered array of ones

import numpy as np array_F = np.ones((4, 3), order='F') print(array_F)

Output:

[[1. 1. 1.] [1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]

Using numpy.arange() Function

The numpy.arange() function creates an array by generating a sequence of numbers based on specified start, stop, and step values. It is similar to Python's built-in range() function.

numpy.arange([start,] stop[, step,] dtype=None, *, like=None)

Example

import numpy as np # Providing just the stop value array1 = np.arange(10) print("array1:", array1) # Providing start, stop and step value array2 = np.arange(1, 10, 2) print("array2:",array2)

Output:

array1: [0 1 2 3 4 5 6 7 8 9] array2: [1 3 5 7 9]

Using numpy.linspace() Function

We can even use the numpy.linspace() function to create an array by specifying the start, stop, and the number of elements we want. The array created by this function consists of evenly spaced values over a specified interval.

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Example

import numpy as np # 10 evenly spaced values from 0 to 5 array1 = np.linspace(0, 5, num=10) print("array1:",array1) # 5 values from 1 to 2, excluding the endpoint array2 = np.linspace(1, 2, num=5, endpoint=False) print("array2:",array2) # Array and returning the step value array3, step = np.linspace(0, 10, num=5, retstep=True) print("array3:",array3) print("Step size:", step)

Output:

array1: [0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5. ] array2: [1. 1.2 1.4 1.6 1.8] array3: [ 0. 2.5 5. 7.5 10. ] Step size: 2.5

Important Difference: linspace() vs arange()

Students often confuse linspace() with arange().

  • np.arange(0, 20, 2) means: Start at 0, increase by 2. (I specify the STEP)
  • np.linspace(0, 20, 11) means: Start at 0, end at 20, and create exactly 11 evenly spaced values. (I specify the NUMBER OF VALUES)

Real-World Examples of linspace()

1. Solar Power Generation ☀️

Suppose your solar plant generates approximately 0 kW at 6 AM and reaches 20 kW at 12 PM. You want readings at 7 equally spaced time points.

import numpy as np power = np.linspace(0, 20, 7) print(power) # Output: [ 0. 3.33333333 6.66666667 10. 13.33333333 16.66666667 20. ]
Why linspace()?
You don't want to manually calculate 0, 3.33, 6.67, 10, etc. Instead, np.linspace(0, 20, 7) means: Start at 0, end at 20, and give me exactly 7 evenly spaced values.
2. Temperature Monitoring 🌡️

Suppose a machine temperature rises from 30°C to 90°C, and you need 13 sample points for a simulation.

temperature = np.linspace(30, 90, 13) print(temperature) # Output: [30. 35. 40. 45. 50. 55. 60. 65. 70. 75. 80. 85. 90.]
3. Speed of a Car 🚗

A car accelerates from 0 km/h to 120 km/h. You want 9 evenly distributed speed values to simulate fuel consumption or braking performance for each speed.

speed = np.linspace(0, 120, 9) print(speed) # Output: [ 0. 15. 30. 45. 60. 75. 90. 105. 120.]
4. Salary Simulation 💰

Suppose you want to test a tax calculation system for salaries from ₹20,000 to ₹1,00,000, using 9 evenly spaced salary values.

salary = np.linspace(20000, 100000, 9) print(salary) # Output: [ 20000. 30000. 40000. 50000. 60000. 70000. 80000. 90000. 100000.] tax = salary * 0.10 print(tax)
5. Camera / Image Processing 📷

Suppose an image-processing algorithm needs brightness levels from 0 to 255, but you only want 10 test values. This can be useful when testing image filters at different brightness levels.

brightness = np.linspace(0, 255, 10) print(brightness)
Classroom Example 🎓

Ask students: A water tank has a capacity of 5000 liters. Create 11 equally spaced water-level values from empty to full.

water = np.linspace(0, 5000, 11) print(water) # Output: [ 0. 500. 1000. 1500. 2000. 2500. 3000. 3500. 4000. 4500. 5000.]

Using numpy.random.rand() Function

This function is used to create an array of specified shape filled with random values sampled from a uniform distribution over [0, 1).

numpy.random.rand(d0, d1, ..., dn)

Example

import numpy as np # Generating a single random float random_float = np.random.rand() # Generating a 1D array of random floats array_1d = np.random.rand(5) # Generating a 2D array of random floats array_2d = np.random.rand(2, 3) # Generating a 3D array of random floats array_3d = np.random.rand(2, 3, 4)

Using numpy.empty() Function

This function initializes an array without initializing its elements; the content of the array is arbitrary and may vary.

numpy.empty(shape, dtype=float, order='C')

Example

import numpy as np empty_array = np.empty((2, 3)) print(empty_array)

Output:

[[1.13750619e-313 0.00000000e+000 0.00000000e+000] [0.00000000e+000 0.00000000e+000 0.00000000e+000]]

Using numpy.full() Function

Using the numpy.full() function, we can create an array with a desired shape and set all the elements in it to a specific value.

numpy.full(shape, fill_value, dtype=None, order='C')

Example

import numpy as np array1 = np.full((2, 3), 5) print(array1)

Output:

[[5 5 5] [5 5 5]]

Practice Questions ✍️

Q1. Integer Conversion

Create an array: arr = np.array([10, 20, 30, 40])

Create another array where the datatype is explicitly set to float.

Expected Concept: dtype=float

Q2. Integer Size

Create an array [100, 200, 300, 400] with dtype=np.int32.

Then create another with dtype=np.int64.

Compare their dtype attributes.

Q3. Classroom Attendance

Create an array of 10 students, where initially every student is marked as present:

[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

Q4. Matrix Initialization

Create a 3 × 4 matrix containing only 1s.

Expected Output:

[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]

Q5. Bank Account Initialization

Create an array for 8 bank accounts, where the initial balance of every account is ₹0.

Q6. Image Processing

Create a 5 × 5 matrix containing zeros.

Think of this as a blank grayscale image.

Q7. Normalized Temperature Readings

Generate 24 random values between 0 and 1 representing normalized temperature readings for 24 hours.

Then, find out the maximum and minimum temperature from the 24 hours.

Q8. Random Student Percentage

Generate 10 random values between 0 and 1 and convert them into percentages between 0 and 100.

Q9. Even Numbers

Create an array of all even numbers between 2 and 50.

Q10. Odd Numbers

Create an array of all odd numbers between 1 and 50.

Q11. Sales Simulation

A shop wants to simulate sales for 30 days.

  • Create Day numbers from 1 to 30 using np.arange().
  • Generate random sales values between ₹1,000 and ₹10,000 using np.random.rand().

Then find:

  • Total sales
  • Average sales
  • Maximum sales
  • Minimum sales

Functions Used for Creation of NumPy Arrays

Basic Array Creation

FunctionsDescription
array()used to create a numpy array
asarray()Convert the input to an array
asanyarray()Convert the input to an ndarray, but pass ndarray subclasses through
copy()Return an array copy of the given object

Array Creation with Specific Shapes and Data

FunctionsDescription
zeros()Return a new array of given shape and type, filled with zeros
ones()Return a new array of given shape and type, filled with ones
empty()Return a new array of given shape and type, without initializing entries
full()Return a new array of given shape and type, filled with fill_value

Array Creation with Sequences

FunctionsDescription
arange()Return evenly spaced values within a given interval
linspace()Return evenly spaced numbers over a specified interval.
logspace()Return numbers spaced evenly on a log scale.

Special Arrays

FunctionsDescription
eye()Return a 2-D array with ones on the diagonal and zeros in all other positions
identity()Return the identity array.
diag()Extract a diagonal or construct a diagonal array
fromfunction()Construct an array by executing a function over each coordinate
fromfile()Construct an array from data in a text or binary file

Random Arrays

FunctionsDescription
random.rand()Random values in a given shape
random.randn()Return a sample from the standard normal distribution
random.randint()Return random integers from low (inclusive) to high (exclusive)
random.random()Return random floats in the half-open interval [0.0, 1.0)
random.choice()Generates a random sample from a given 1-D array

Structured Array

FunctionsDescription
zeros_like()Return an array of zeros with the same shape and type as a given array
ones_like()Return an array of ones with the same shape and type as a given array.
empty_like()Return a new array with the same shape and type as a given array
full_like()Return a full array with the same shape and type as a given array