Python Arrays

Python has no built-in array type the way C does. Day to day you use a Python list. This page is for the remaining cases: the array module, and when to switch to NumPy.

Python Arrays

If you searched for “Python arrays” because you want a list of values you can loop over, start with the Python lists tutorial. Lists are the default sequence in Python: mixed types, easy appends, slicing.

Use this page when you need a typed, compact sequence (array.array) or a numeric grid (NumPy arrays). Do not treat this chapter as a second lists tutorial.

Arrays

Arrays are used to store multiple values in one single variable:

Example - Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Access the Elements of an Array

You refer to an array element by referring to the index number.

Example - Get the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)

Example - Modify the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Example - Return the number of elements in the cars array:

cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)

Note: The length of an array is always one more than the highest array index.

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example - Print each item in the cars array:

cars = ["Ford", "Volvo", "BMW"]
for x in cars:
    print(x)

Adding Array Elements

You can use the append() method to add an element to an array.

Example - Add one more element to the cars array:

cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)

Removing Array Elements

You can use the pop() method to remove an element from the array.

Example - Delete the second element of the cars array:

cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
print(cars)

You can also use the remove() method to remove an element from the array.

Example - Delete the element that has the value "Volvo":

cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)

Note: The list's remove() method only removes the first occurrence of the specified value.

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

append()
Adds an element at the end of the list
clear()
Removes all the elements from the list
copy()
Returns a copy of the list
count()
Returns the number of elements with the specified value
extend()
Add the elements of a list (or any iterable), to the end of the current list
index()
Returns the index of the first element with the specified value
insert()
Adds an element at the specified position
pop()
Removes the element at the specified position
remove()
Removes the first item with the specified value
reverse()
Reverses the order of the list
sort()
Sorts the list

The Array Module

Python has a built-in array module that provides a more efficient way to work with arrays of numeric data.

Example - Import and use the array module:

import array

# Create an array of integers
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers)

# Create an array of floats
floats = array.array('f', [1.1, 2.2, 3.3, 4.4])
print(floats)

Array Type Codes

'b'
signed char (1 byte)
'B'
unsigned char (1 byte)
'h'
signed short (2 bytes)
'H'
unsigned short (2 bytes)
'i'
signed int (4 bytes)
'I'
unsigned int (4 bytes)
'f'
float (4 bytes)
'd'
double (8 bytes)

Array Module Methods

Example - Working with array methods:

import array

# Create an array
arr = array.array('i', [1, 2, 3, 4, 5])

# Append an element
arr.append(6)
print(arr)  # array('i', [1, 2, 3, 4, 5, 6])

# Insert an element at specific position
arr.insert(0, 0)
print(arr)  # array('i', [0, 1, 2, 3, 4, 5, 6])

# Remove an element
arr.remove(3)
print(arr)  # array('i', [0, 1, 2, 4, 5, 6])

# Pop an element
popped = arr.pop()
print(f"Popped: {popped}")  # Popped: 6
print(arr)  # array('i', [0, 1, 2, 4, 5])

# Get array info
print(f"Length: {len(arr)}")
print(f"Type code: {arr.typecode}")
print(f"Item size: {arr.itemsize} bytes")

NumPy Arrays

For more advanced array operations, Python developers often use NumPy, which provides powerful array operations:

Example - NumPy array (requires installation: pip install numpy):

import numpy as np

# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print(arr)

# Array operations
print(arr * 2)      # Multiply all elements by 2
print(arr + 10)     # Add 10 to all elements
print(arr.sum())    # Sum of all elements
print(arr.mean())   # Mean of all elements

# 2D array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
print(matrix.shape)  # (2, 3)

When to Use Each Type

Python Lists

  • General-purpose, flexible
  • Can store different data types
  • Good for most applications
  • Built-in to Python

Array Module

  • More memory efficient
  • Only stores one data type
  • Good for large numeric datasets
  • Built-in to Python

NumPy Arrays

  • Fastest for numerical operations
  • Advanced mathematical functions
  • Multi-dimensional arrays
  • Requires separate installation

List vs array vs NumPy

In Python, "array" can mean three different things. Choose based on your data.

TypeImportUse for
listbuilt-inGeneral mixed-type sequences
array.arrayfrom array import arrayCompact single-type numeric data
numpy.ndarrayimport numpy as npFast vectorized math, matrices
import numpy as np

a = np.array([1, 2, 3, 4])
print(a * 2)        # [2 4 6 8]  -> elementwise, no loop
print(a.mean())     # 2.5
print(a[a > 2])     # [3 4]  -> boolean filtering

Try It Yourself

Exercise 1: Loop through a list of cars and print each one with its index.

Show solution
cars = ["Ford", "BMW", "Volvo"]
for i, car in enumerate(cars):
    print(i, car)

Exercise 2: Using NumPy, create an array of 1–5 and print the sum of its squares.

Show solution
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print((a ** 2).sum())   # 55

Key Takeaways

  • Python has no native fixed array — the list is the everyday sequence.
  • Use array.array for compact same-type numbers.
  • Use NumPy for fast, vectorized numeric work.

📘 Real-World Deep Dive

Python has no built-in "array" type in the C sense — a <code>list</code> does the job 95% of the time. The 5% where it doesn't (millions of numbers, fixed-width binary, tight memory) is exactly where knowing <code>array.array</code> and NumPy saves you from a slow, RAM-hungry program.

Real-Life Scenario

A weather station streams a temperature reading every minute. We keep the last N readings and report a moving average — the kind of rolling buffer you meet in monitoring, audio, and IoT code.

Real-Life Example

from collections import deque

class RollingAverage:
    def __init__(self, window: int):
        self.readings = deque(maxlen=window)   # drops the oldest automatically

    def add(self, value: float) -> float:
        self.readings.append(value)
        return sum(self.readings) / len(self.readings)

temps = RollingAverage(window=3)
for reading in [20.1, 20.4, 21.0, 22.5, 23.1]:
    print(f"{reading:5.1f} -> avg {temps.add(reading):.2f}")

A deque with maxlen is the idiomatic fixed-size buffer — no manual slicing to trim the front.

Expected Output

 20.1 -> avg 20.10
 20.4 -> avg 20.25
 21.0 -> avg 20.50
 22.5 -> avg 21.30
 23.1 -> avg 22.20

Common mistakes

  • A plain list grows without bound. If you only ever need the last N items, use deque(maxlen=N) so old items fall off on their own.
  • Trimming with lst = lst[1:] in a loop looks harmless but rebuilds the whole list every time — O(n) per step, O(n²) overall.
  • Reaching for NumPy to store 20 numbers is overkill; reaching for a list to store 20 million floats will eat gigabytes. Match the tool to the size.

🚀 Performance & Best Practices

  • array.array('d', ...) stores raw doubles — roughly 8 bytes each vs. ~28 for a Python float object in a list.
  • For any real math on numeric arrays (sums, dot products, filtering), a NumPy array is both shorter to write and 10–100× faster than a Python loop.
  • deque.append / popleft are O(1); doing the same at the front of a list is O(n).

🧪 Try It Yourself

  1. Extend RollingAverage with a max() method that reports the largest reading still in the window.
  2. Swap the deque for a plain list and print both — convince yourself the memory keeps growing.
  3. Rewrite the averaging with numpy and time both versions over 1,000,000 readings.

FAQ: Python Arrays

Common questions about this page.

What is Python Arrays?

Python Arrays is a Python Tutorial lesson that explains python arrays in Python. Python has no built-in array type like C. This lesson explains when people say “array,” how lists fill that role, and when to use the array module or NumPy. It is written for beginners who want a clear definition and working examples.

Should I run python arrays examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python arrays in this Python Tutorial Python lesson (Python Arrays).

How do I use python arrays in Python?

To use python arrays in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python arrays?

This Python Arrays tutorial shows python arrays syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Arrays example for beginners

Yes. This page includes a beginner python arrays example you can copy and run. It is designed for searches such as "python arrays for beginners", "python arrays example", and "how to use python arrays".

What are common mistakes with python arrays?

Common python arrays mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python arrays?

Python Arrays is used in real Python work. Learning python arrays helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Arrays free to learn online?

Yes. You can learn python arrays free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.