Python Array Example: 13 Operations

Working with a sequence of values in Python starts with choosing how to represent those values. The array module lets you create an array by choosing a type code and supplying starting values.

This article demonstrates array operations and compares Python arrays with lists and NumPy.

TL;DR

Use Python’s array module when a sequence should store values of one numeric type, and choose its type code before building the array.

  • Import the array module.
  • Choose a type code when creating values.
  • Use the length function, indexing, slicing and sequence methods to work with the values.
  • Choose a list for general-purpose Python objects or NumPy for multidimensional numerical work.

What Is a Python Array?

The type code determines how each value in an array is represented.

Check itemsize to see the number of bytes used by each item on this platform.

The example below records the values before and after common operations.

How to Create and Use a Python Array

The command is python3 array_operations.py. I ran it and placed its output beside the terminal capture.

Step 1: Choose a type code and create values

I use the array constructor with type code i to build signed integers from a list.

  • i: signed integer values
  • f: floating-point values
  • d: double-precision floating-point values

The table lists three numeric choices. Their item size can depend on the platform, so check itemsize when memory layout matters. The module is part of Python’s standard library.

import array
values = array.array("i", [12, 7, 12, -3])
print(values)
print("length:", len(values))

Output from the full example:

array('i', [12, 7, 12, -3])
length: 4
last: -3
slice: array('i', [7, 12])
updated: array('i', [9, 7, 12, -3, 8, 10])
removed: 5
count of 12: 1
index of 10: 5
as list: [9, 7, 12, -3, 8, 10]
Terminal output from Python array operations
Running the array operations example

The output shows the initial values, their count and selected items.

To create an array, pass the type code first and the starting values second. A list or another iterable can provide those values. For data that arrives one item at a time, create an empty array and keep its type code fixed.

Printing an array shows its items and type code. The example also prints its length, making the item count explicit.

Step 2: Read values by index and slice

Use an index to read one value and a slice to select a range without changing the source.

values[-1]   # final value: -3
values[1:3]  # array('i', [7, 12])

The slice starts at index one and stops before index three, returning the selected items separately.

Step 3: Add and remove elements

The example applies sequence methods to change the values. I chose pop for the final removal because it returns the removed value.

values.append(5)
values.insert(1, 9)
values.remove(12)
removed = values.pop()
values.extend([8, 10])

All added values must fit the array’s type code, so convert incoming data before extending when its type differs.

Remove deletes the first matching value. Pop removes by position and returns that value, which makes it useful when the next calculation needs the removed item.

Step 4: Search, count and convert values

Use the index method to find the first matching position and the count method to count matches. Convert to a regular list when an API expects that type.

values.count(12)  # 1
values.index(10)  # 5
values.tolist()   # [9, 7, 12, -3, 8, 10]

A search or removal for a missing value raises ValueError. Check membership first when absence is a normal possibility.

Which Python Array Should You Use?

The choice affects which operations fit the data model.

For the list option, see AskPython’s guide to the Python list. For arrays with rows and columns, see its guide to NumPy arrays.

If you only need to set up initial values, see AskPython’s guide to initializing an array in Python. Its examples complement the operations here.

Python Array Edge Cases

Python documents its supported type codes and platform-specific sizes. I checked the official table because a value outside the chosen type’s range can raise an error.

CaseWhat happensWhat to do
Index outside the arrayReading or assigning raises IndexErrorCheck len(values)
Value is absentremove() or index() raises ValueErrorTest membership first
Need two dimensionsarray.array is one-dimensionalUse nested lists or NumPy
Need portable bytestobytes() uses machine representation and byte orderDefine an interchange format explicitly

The legacy ‘u’ Unicode type code is deprecated since Python 3.3 and the current documentation schedules its removal in Python 3.16. It recommends ‘w’ instead. Do not copy old examples that assume ‘u’ is the current choice.

For portable binary interchange, define widths and byte order in the format contract. Raw bytes reflect machine representation and byte order.

Conclusion: Choose the Sequence for the Job

The runner renders the title once, so this conclusion leaves the comparison to the preceding table.

FAQ

The FAQ answers common naming and structure questions.

Are arrays and lists the same?

No. A Python list holds general Python objects, while array.array stores values represented by one selected type code. Both are mutable sequences, but their data models differ.

How do you find the length of a Python array?

Call len(values). It returns the number of items in the array.

Can array.array hold two dimensions?

No. array.array is one-dimensional. Use nested lists or NumPy when you need rows and columns.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 260