Create an Array in Python

You can create an array in Python with a list for general-purpose data, the built-in array module for typed values, or a NumPy array for numerical and multidimensional work. Python lists are the usual choice for everyday collections; NumPy is usually the better choice when you need matrix-like data, math operations, or a predictable numeric shape. This guide shows each option, including 2-D arrays, CSV data, user input, and common indexing mistakes.

What an Array Means in Python

An array is an ordered collection of values. Each value has a position, called an index, and Python indexes start at 0.

Python does not use one universal “array” type for every task:

  • A list is Python’s default flexible sequence. It can grow and hold mixed types.
  • An array.array object is a standard-library sequence restricted to one underlying type, such as signed integers.
  • A NumPy ndarray is designed for numeric data, including 2-D tables and higher-dimensional data.

Use a Python list when values may mix types or grow freely; use a NumPy array when you need numeric data in a deliberate one- or two-dimensional layout.

For example, a list can contain values of different types:

items = [1, "hello", True]

That flexibility is useful for application data, but it is usually not what you want for numerical calculations.

How to Create an Array in Python

Choose the collection type before you start adding values. This table helps match the task to the right tool.

Need Best choice Why
A flexible collection that may contain strings, numbers, or objects Python list Built in and easy to grow
A compact standard-library collection of one type array.array Restricts values to a defined type
Numeric calculations, matrices, or scientific data NumPy array Supports shapes, vectorized operations, and 2-D layouts

Step 1: Choose the Collection for Your Data

  1. Use a list when you are collecting general application values, parsing input, or building a sequence gradually.
  2. Use array.array when you specifically need a typed standard-library array.
  3. Use NumPy when the values are numeric and you need operations such as reshaping, stacking, filtering, or matrix-style indexing.

NumPy is an external package. Install it in the active project environment before importing it:

python -m pip install numpy

I use a Python virtual environment for NumPy installs because it keeps project dependencies isolated.

Step 2: Initialize the Array

Create an empty Python list when you plan to append values later:

items = []

Create a list with initial values by placing them between square brackets:

items = [1, "hello", True]

To create a list filled with initial zero values, use list multiplication. This creates a list containing ten zeros:

zeros = [0] * 10

Replace 10 with a variable such as n when the size comes from your program.

Use the standard-library array module when all items should be signed integers:

from array import array

int_values = array("i", [1, 2, 3, 4, 5])

The type code "i" means signed integer. Trying to append a string to this array raises a TypeError.

Create a one-dimensional NumPy array with np.array():

import numpy as np

values = np.array([1, 2, 3])

NumPy also provides convenient numeric sequences. np.arange() uses a step of 1 when you omit the step argument, and it excludes the ending value:

integers = np.arange(0, 10)

np.linspace() creates evenly spaced values and uses 50 points when you omit its third argument:

evenly_spaced = np.linspace(0, 1)

Step 3: Access Values and Confirm the Result

Access an element with square brackets and its zero-based index. The expression b[0] gets the first item:

b = [10, 20, 30]

first = b[0]
print(first)

For a NumPy array, inspect the shape and data type after creating it:

print(values.shape)
print(values.dtype)

A one-dimensional array such as np.array([1, 2, 3]) has a shape of (3,). This confirms that it contains three values in one dimension.

Create a 2-D Array in Python

A 2-D NumPy array is a grid of rows and columns. Each row must have the same number of values for the result to be a regular rectangular array.

Put Vectors Into Columns

Use np.column_stack() when each input vector should become a column. This is useful when each vector represents one measured field, feature, or source of data.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

by_column = np.column_stack([a, b])
print(by_column)

The result is:

[[1 4]
 [2 5]
 [3 6]]

The first column is [1, 2, 3], and the second column is [4, 5, 6]. This column-oriented behavior is supported by Carnegie Mellon Chemical Engineering.

Put Vectors Into Rows

Use np.row_stack() when each input vector should remain a row:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

by_row = np.row_stack([a, b])
print(by_row)

The result is:

[[1 2 3]
 [4 5 6]]

np.vstack([a, b]) produces the same row-oriented layout for one-dimensional vectors.

Select Columns and Split a 2-D Array

Use two indices for a 2-D NumPy array: first the row selection, then the column selection. A colon means “all values” along that axis.

import numpy as np

A = np.array([
    [1, 2, 3, 5],
    [4, 5, 6, 9]
])

third_column = A[:, 2]
print(third_column)

A[:, 2] selects all rows from the third column. It returns:

[3 6]

To split the same array into two equal sections across its columns, use np.hsplit(A, 2):

left, right = np.hsplit(A, 2)

print(left)
print(right)

The array has four columns, so splitting it into two sections produces two-column arrays. The number of columns must divide evenly by the number of requested sections.

Create Arrays From CSV Files and User Input

Create a NumPy Array From a CSV File

For a headerless CSV file containing only numeric values, read the rows with Python’s csv module and convert them into a NumPy array.

import csv
import numpy as np

with open("data.csv", newline="", encoding="utf-8") as file:
    rows = [[float(value) for value in row] for row in csv.reader(file)]

data = np.array(rows)

print(data)
print(data.shape)

The csv.reader() function returns text values, so float(value) converts each field into a numeric value before NumPy creates the array.

If the first row contains column names, read that header separately instead of converting it to float. Keep the header as a list of labels and convert only the remaining numeric rows into the array.

Create an Array From User Input

Use input() to collect text, split it into separate values, and convert each value to the type you need.

text = input("Enter integers separated by spaces: ")

numbers = [int(value) for value in text.split()]

print(numbers)

If the user enters:

4 8 15 16

the resulting list is:

[4, 8, 15, 16]

Use float(value) instead of int(value) when decimal values are valid. Avoid eval() for input conversion because it can execute arbitrary Python code.

Check Arrays and Avoid Common Mistakes

After creating an array, verify both its values and its structure. For NumPy arrays, print the array, its shape, and its data type:

print(data)
print(data.shape)
print(data.dtype)

Use this checklist before continuing with calculations:

  • Confirm that list values appear in the expected order.
  • Confirm that a NumPy array has the intended shape, such as rows by columns.
  • Confirm that numeric data has a numeric type rather than strings.
  • Confirm that every row in a 2-D array has the same number of values.
  • Confirm whether source vectors became rows or columns after stacking.

Be careful when using list multiplication with nested mutable objects. A pattern such as repeating the same inner list can make multiple rows refer to one shared list, so changing one row changes them all. Use a list comprehension when you need separate nested lists.

Next, choose the collection type that matches your data, run the smallest example that fits your case, and inspect its values and shape before building more logic around it.

Frequently Asked Questions

How Do I Create an Empty Array in Python?

For most Python programs, create an empty list with items = []. For an empty typed standard-library integer array, use array("i"); for an empty NumPy array, use np.array([]).

items = []

An empty collection can be filled later with list methods such as append() or by constructing a new NumPy array from your finished data.

How Do I Create an Array in Python of Size n?

For a list of ten zero values, use [0] * 10; replace 10 with n when the size is stored in a variable. This is appropriate for immutable starting values such as integers.

n = 10
zeros = [0] * n

For a numeric NumPy array initialized with zeros, use np.zeros(n, dtype=int) when you need integer values.

How Do I Turn an Array Into a Set in Python?

Use set(values) to remove duplicate values from a Python list. A set is unordered, so do not use it when preserving the original order matters.

values = [1, 2, 2, 3, 3, 3]

unique_values = set(values)
print(unique_values)

For a one-dimensional NumPy array, convert it to a list first with set(data.tolist()).

Does Python Have a Built-In Multidimensional Array?

Python lists can represent multiple dimensions by nesting lists, such as a list of rows. For numeric 2-D and higher-dimensional data, NumPy arrays are usually easier to inspect, index, stack, and calculate with.

import numpy as np

matrix = np.array([
    [1, 2],
    [3, 4]
])

The NumPy array has a predictable rectangular shape, which is important for matrix-style operations.