October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

2D Arrays in Python: Nested Lists and NumPy, With Examples

See how Python nested lists and NumPy represent 2D data, with examples for creation, shape, indexing, arithmetic, broadcasting, and copies.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Python, you can represent a 2D structure with a list of lists, or use a NumPy ndarray for multidimensional numerical work. A nested list is flexible and needs no extra package; a NumPy array adds explicit dimensions, a common element type, and concise array arithmetic.

Make a 2D structure with nested lists

Each inner list represents a row. For a rectangular grid, make every row the same length:

rows = [
    [1, 2],
    [3, 4],
    [5, 6],
]

print(rows[0][1])  # 2

Python uses zero-based indexing: rows[0] selects the first row, and the second index selects an item within that row. Built-in lists can also hold rows of different lengths, but such a value is not a regular rectangle. Check row lengths if your code relies on a grid with consistent columns. The Python tutorial’s list examples describe a matrix as a list of equal-length lists.

Convert the nested list to a NumPy array

Pass the nested sequence as one argument to np.array(). NumPy creates an array with dimensions inferred from the nesting and values:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import numpy as np

array = np.array(rows)
print(array)
print(array.shape)  # (3, 2)
print(array.ndim)   # 2
print(array.size)   # 6
print(array.dtype)  # inferred from the values

The properties answer different questions: shape gives the length of each axis, ndim gives the number of axes, size gives the total number of elements, and dtype gives the element type. If your code requires a particular numeric representation, specify it rather than relying on inference:

floats = np.array([[1, 2], [3, 4]], dtype=np.float64)

NumPy’s array creation guide covers construction from nested sequences, data types, and shape-based constructors.

Create arrays by shape or reshape values

When you know the desired dimensions, constructors such as zeros and ones can be clearer than writing every element. You can also reshape a sequence when its element count matches the requested dimensions:

zeros = np.zeros((2, 3))
ones = np.ones((2, 3), dtype=int)

sequence = np.arange(6).reshape(2, 3)

The shape tuple is (rows, columns) here. reshape(2, 3) requires six values, because the requested shape contains six positions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Select an element, row, or column

For a nested list, use chained indexing. For a NumPy array, use comma-separated indexes for separate axes:

rows = [[10, 11, 12], [20, 21, 22]]
array = np.array(rows)

rows[0][1]       # 11
array[0, 1]      # 11
array[1]         # second row
array[:, 0]      # first column
array[0:2, 1:]   # rows 0–1, columns 1 onward

The colon selects all positions along an axis; a slice such as 1: selects from index 1 onward. In a built-in list, rows[0, 1] is not the usual row-and-column notation: a list expects one index, while NumPy arrays support a tuple of axis indexes. For more examples, see the NumPy beginner guide to indexing.

Use NumPy for elementwise arithmetic and broadcasting

Ordinary list operations are not elementwise numeric matrix operations. NumPy arithmetic applies operations to array elements:

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

array + 10
# array([[11, 12],
#        [13, 14]])

NumPy can also broadcast a compatible smaller shape across a larger one. Here the one-dimensional operand has two values, so it applies across the two columns of each row:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
array * np.array([10, 100])
# array([[ 10, 200],
#        [ 30, 400]])

Broadcasting is not arbitrary alignment: the dimensions must be compatible under NumPy’s rules. Its documentation defines broadcasting as how NumPy treats arrays with different shapes during arithmetic. Broadcasting can avoid materializing repeated copies, although some shape combinations can still have inefficient memory behavior. See the NumPy broadcasting guide for the compatibility rules.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Know when a NumPy slice changes the original

Basic NumPy slicing commonly returns a view that refers to the original array’s data. Editing that view can therefore change the original:

original = np.array([[1, 2], [3, 4]])
row_view = original[0]
row_view[0] = 99

print(original[0, 0])  # 99

Call .copy() when you need independent array data:

independent = original[0].copy()
independent[0] = -1

print(original[0, 0])  # still 99

Python list slicing creates a new outer list, but it does not recursively copy mutable objects inside that list. NumPy explains the view behavior and explicit-copy option in its copies and views guide.

Choose lists or NumPy based on the work

Consideration Nested Python lists NumPy ndarray
Structure Flexible sequences of Python objects; rows can be handled as lists. Multidimensional structure with a shape and element dtype.
Indexing Chained indexes, such as rows[1][2]. Comma-separated axis indexes, such as array[1, 2], plus multidimensional slicing.
Numeric operations Use loops or other code to express elementwise calculations. Elementwise arithmetic and broadcasting support concise numerical calculations.
Slicing A slice makes a new list containing references to selected elements. A basic slice commonly returns a view; use .copy() for independent data.
Good fit Small, flexible, general-purpose nested data without a need for numerical array operations. Regular numerical data where multidimensional operations, dtype control, or array indexing are useful.

Use nested lists when their flexibility is enough. Choose NumPy when your data is a regular numerical grid and you want operations over whole arrays. The official documentation describes these behaviors and examples, but does not establish a universal speed or memory advantage for every workload; such comparisons depend on the data, operation, and environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.