Back to Python Notes
Topic #242

Creating Arrays

By the end of this lesson, you will be able to create NumPy arrays from existing Python data structures and initialize empty or filled arrays with specific shapes.

What it is

In scientific computing with Python, an array is a grid of values, all of the same type, indexed by a tuple of non-negative integers. While Python has built-in lists, they are inefficient for numerical operations. The numpy library provides the ndarray object, which allows for fast vectorized calculations.

The mental model is a spreadsheet: rows and columns where every cell holds a number (or string) of the exact same kind. Related terms include shape (dimensions), dtype (data type), and axis (direction of operation).

Why it matters

  • Performance: NumPy arrays store data in contiguous memory blocks, making them significantly faster than Python lists for large datasets.
  • Vectorization: You can perform mathematical operations on entire arrays without writing explicit loops.
  • Interoperability: Most machine learning libraries (like scikit-learn and TensorFlow) expect input data as NumPy arrays.
  • Memory Efficiency: Arrays enforce a single data type, reducing overhead compared to mixed-type lists.

Syntax or steps

To work with arrays, you must first import the library. There are two primary ways to create arrays:

  1. From Data: Convert a list or nested list using np.array().
  2. From Scratch: Create arrays filled with zeros, ones, or random numbers using functions like np.zeros(), np.ones(), or np.random.rand().

Example

import numpy as np

# 1. Creating an array from a Python list
data_list = [10, 20, 30, 40]
arr_from_list = np.array(data_list)

# 2. Creating a 2D array (matrix) from nested lists
matrix_data = [[1, 2], [3, 4]]
arr_2d = np.array(matrix_data)

# 3. Initializing an array of zeros with shape (2, 3)
zeros_arr = np.zeros((2, 3))

print("Array from list:", arr_from_list)
print("2D Array:\n", arr_2d)
print("Zeros Array:\n", zeros_arr)

Explanation:

  • np.array(data_list) converts the standard Python list into a NumPy array. If the elements are integers, the resulting array usually defaults to int64.
  • np.array(matrix_data) creates a two-dimensional array because the input contains nested lists. The shape becomes (2, 2).
  • np.zeros((2, 3)) generates a new array filled with floating-point zeros. The argument (2, 3) specifies the shape: 2 rows and 3 columns.

Common mistakes

  • Mixed Types: Passing a list with both strings and integers to np.array() forces all elements to become strings, preventing math operations. Ensure your source data is homogeneous.
  • Incorrect Shape Syntax: For functions like np.zeros(), you must pass a tuple for dimensions. Use np.zeros((2, 3)), not np.zeros(2, 3).
  • Modifying Original Data: Sometimes changes to an array affect the original list if views are used incorrectly. Use .copy() if you need an independent duplicate.
  • Forgetting Imports: Always start with import numpy as np; otherwise, np is undefined.

When to use it

Compare NumPy arrays with Python lists to choose the right tool.

Feature Python List NumPy Array
Data Types Heterogeneous (mixed types allowed) Homogeneous (single type enforced)
Math Operations Slow; requires loops Fast; supports vectorization
Best For General purpose storage, small collections Numerical analysis, matrices, big data

Practice

Guided Exercise: Create a 3x3 array filled entirely with the number 5. Hint: Use np.full() or multiply np.ones() by 5.

Challenge: Create a 2D array representing a diagonal matrix of size 4x4 with values 1, 2, 3, 4 on the diagonal and zeros elsewhere. Hint: Look up np.diag().

Quick check

Question: What happens if you try to add two NumPy arrays of different shapes?

Answer: It raises a ValueError unless the shapes are compatible via broadcasting rules (e.g., adding a scalar or a 1D array to a 2D array under specific conditions). Strictly speaking, identical shapes are required for element-wise addition without broadcasting.

Summary

NumPy arrays are the foundation of numerical computing in Python, offering speed and structure that standard lists cannot match. By mastering np.array() for conversion and initialization functions like np.zeros(), you enable efficient data manipulation for complex algorithms.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Creating Arrays – FAQs

Quick answers about learning Creating Arrays in Python.

This free note from Coding Now Tech Institute explains Creating Arrays in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Creating Arrays, is 100% free with no signup required.
With focused practice, most students grasp Creating Arrays in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now