Python Array & How To Use Them [With Examples]

Understand Python arrays and how they optimize memory and performance in numeric tasks. Learn to work with both array and NumPy, complete with real-world examples and best practices.

Python

The process of handling data in Python requires storing several values simultaneously. Arrays constitute the most efficient data storage approach when you work with numerical information. The built-in Python lists have specific use cases where arrays provided through the array module along with NumPy libraries demonstrate superior efficiency.

In this article, you’ll learn what arrays are in Python, how to create and manipulate them, and when to use them over lists with practical code examples to reinforce each concept.

What Is an Array in Python?

A data structure named array contains several elements of the same data type stored under a single variable. Arrays provide better performance and memory efficiency when managing extensive datasets, although lists allow storing different data types together.

In Python, arrays can be created using:

  • The built-in array module
  • The NumPy library (for scientific computing)

Master Python with the Master Python Programming course, covering everything from basics to advanced concepts through hands-on projects. Perfect for beginners and upskillers alike.

Core Concepts Behind Arrays

  1. Homogeneous Data Storage: Arrays store only one data type, making them faster and more memory-efficient than lists for large-scale numeric data.
  2. Contiguous Memory Allocation: Arrays allocate memory blocks contiguously, enabling quicker access to elements using index-based lookups.
  3. Typecode Mapping: Python’s array module requires specifying a typecode to define the type of data:

    import array
    arr = array.array(‘i’, [1, 2, 3])  # ‘i’ = signed int
  4. Buffer Interface Compatibility: Arrays support Python’s buffer interface, allowing fast communication with I/O operations and libraries like NumPy or struct.
  5. Serialization Ready: Arrays can be easily converted to bytes using .tobytes() and reconstructed using .frombytes(), useful for low-level data transmission.
  6. Efficiency in Loops and Iterations: Arrays reduce overhead during iterative numeric operations when compared to lists.

Python Array Typecodes

Common typecodes used with array.array()

TypecodeData TypeExample
‘i’Signed integerarray(‘i’, [1, -2, 3])
‘I’Unsigned integerarray(‘I’, [1, 2, 3])
‘f’Floating pointarray(‘f’, [1.1, 2.2, 3.3])
‘d’Double precision floatarray(‘d’, [1.1, 2.2, 3.3])
‘b’Signed chararray(‘b’, [65, 66, 67])
‘u’Unicode characterarray(‘u’, [‘a’, ‘b’, ‘c’])

Python Array Operations (Using the array Module)

In Python, the array can be handled by a module called “array”, which is helpful if we want to manipulate a single type of data value. Below are two important terms that can help in understanding the concept of an array.

  1. Element: Each item stored in an array is called an element.
  2. Index: The location of each element is defined by a numerical value called index. Each element in an array has an index value by which it can be identified.

Array Representation

The array can be declared in multiple ways depending upon the programming language we are using. But few points are important that need to consider while working with an array:

  1. The starting index of an array is 0
  2. Each element in an array is accessible by its index
  3. The length or size of an array determines the capacity of the array to store the elements

The syntax for Array Representation

arrayName = array.array (dataType, [array,items])
import array
arr = array.array('i', [10, 20, 30, 40, 50])

1. Access Elements

print(arr[2])  # Output: 30

2. Modify Element

arr[2] = 35
print(arr)  # Output: array('i', [10, 20, 35, 40, 50])

3. Append Element

arr.append(60)

4. Insert Element

arr.insert(1, 15)  # Insert 15 at index 1

5. Remove Element by Value

arr.remove(40)  # Removes the first occurrence of 40

6. Pop Element by Index

arr.pop()      # Removes last element
arr.pop(2)     # Removes element at index 2

7. Extend Array

arr2 = array.array('i', [70, 80])
arr.extend(arr2)

8. Index of Element

print(arr.index(50))  # Returns index of 50

9. Reverse Array

arr.reverse()

10. Buffer Info

print(arr.buffer_info())  # Returns memory address and length

11. Count Occurrences

print(arr.count(20))  # Count how many times 20 appears

12. Convert Array to List

arr_list = arr.tolist()

NumPy Array Operations

import numpy as np
np_arr = np.array([1, 2, 3, 4, 5])

1. Element-wise Arithmetic

print(np_arr + 10)         # [11 12 13 14 15]
print(np_arr * 2)          # [2 4 6 8 10]
print(np_arr ** 2)         # [1 4 9 16 25]

2. Aggregate Functions

print(np_arr.sum())        # 15
print(np_arr.mean())       # 3.0
print(np_arr.min())        # 1
print(np_arr.max())        # 5
print(np_arr.std())        # Standard deviation

3. Slicing

print(np_arr[1:4])         # [2 3 4]

4. Shape and Reshape

arr2D = np.array([[1, 2], [3, 4]])
print(arr2D.shape)         # (2, 2)
print(arr2D.reshape(4, 1))

5. Add Row/Column

np.append(np_arr, [6, 7])

6. Stack Arrays

a = np.array([1, 2])
b = np.array([3, 4])
print(np.hstack((a, b)))   # Horizontal stack: [1 2 3 4]
print(np.vstack((a, b)))   # Vertical stack

7. Transpose Matrix

print(arr2D.T)

8. Logical Operations

print(np_arr > 3)          # [False False False  True  True]
print(np_arr[np_arr > 3])  # [4 5]

9. Sorting

unsorted = np.array([3, 1, 5, 2])
print(np.sort(unsorted))   # [1 2 3 5]

10. Unique Elements

print(np.unique(np.array([1, 2, 2, 3, 3, 3])))

Pro Tip: Use NumPy if you’re working with large datasets or numerical computations. It’s fast, efficient, and designed for performance.

Difference Between Python List and Array

While both lists and arrays can be used to store sequences of elements, they serve different purposes and have different performance characteristics. Understanding their differences is crucial when writing efficient Python code.

FeaturePython List ([])Python Array (array.array)
ModuleBuilt-in, no import neededRequires import array module
Data TypeCan store mixed types like int, str, float, etc.Only one data type (specified by a typecode like ‘i’, ‘f’)
Type CheckingDynamic typing — flexibleType-safe — enforces uniform data type
PerformanceSlower for numeric operationsFaster for numerical data due to low-level optimization
Memory UsageHigher memory consumption due to dynamic typingMore memory-efficient for large numeric data
FunctionalityRich set of built-in list methodsLimited to array-specific numeric operations
Syntax SimplicityExtremely beginner-friendly, intuitive syntaxSlightly complex (requires understanding of typecodes)
Use CaseGeneral-purpose — ideal for small, mixed-type collectionsIdeal for numerical operations on large data sets
Type SafetyNot type-safe — allows inconsistent typesType-safe — raises error on type mismatch
ConversionNot requiredCan convert to list using .tolist() method

Use arrays when:

  • You are working with large datasets of numbers
  • You require efficient mathematical operations
  • Memory optimization is a concern

Applications of Python Arrays

Python Arrays are used in:

  • Numerical computation (NumPy)
  • Signal and image processing
  • Scientific simulations
  • Financial modeling
  • Machine learning pipelines

Explore the Data Science with Python course to build foundational skills in statistics, data visualization, and regression modeling through hands-on Python practice.

Best Practices for Using Arrays in Python

  • Use NumPy for numerical tasks.
  • Prefer lists for general-purpose programming.
  • Always validate data types when using the array module.
  • Leverage vectorized operations to optimize performance with NumPy.

Common Pitfalls to Avoid

  • Trying to store mixed data types in a native array
  • Forgetting to import the right module (array or numpy)
  • Using loops instead of vectorized functions in NumPy
  • Confusing shape and length in multidimensional arrays

Frequently Asked Questions (FAQ’s)

What is the difference between array.array and NumPy arrays?

array.array is a built-in Python module suitable for basic numeric arrays, while NumPy arrays offer advanced mathematical operations, faster performance, and support for multi-dimensional data.

Can I create multi-dimensional arrays using the array module?

No, array.array only supports one-dimensional arrays. For multi-dimensional arrays, you should use libraries like NumPy.

How do I check the data type of elements in an array?

You can use the .typecode attribute for array.array. For example,

import array  
arr = array.array('i', [1, 2, 3])  
print(arr.typecode)  # Output: 'i' (integer)

Can I slice arrays like lists in Python?

Yes, both array.array and lists support slicing. For example:

arr[1:3]  # Returns a slice from index 1 to 2

Is it possible to sort an array created with array.array?

Yes, you can use the built-in sorted() function or convert the array to a list, sort it, and convert it back.

How do I search for an element in an array?

Use the .index(value) method to find the index of the first occurrence of a value. If the value is not found, it raises a ValueError.

Can I use array methods with custom objects?

No, array.array is limited to primitive data types like integers and floats. For custom objects, use lists or other data structures.

What happens if I try to add a float to an integer array?

array.array enforces data types. Adding a float to an integer array will raise a TypeError. Use a float array (‘f’) if you need to store decimal values.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top