📚 Python Arrays – Store Multiple Values in One Place | TechTown.in
If you’re looking to store multiple items of the same type — like numbers, scores, or sensor readings — in a single variable, arrays are your best friend.
Although Python offers powerful lists, the traditional array module is still useful when you want to store data efficiently in memory, especially for numeric data.
Let’s dive into what Python arrays are, how they work, and when you should use them.
🧠 What is an Array?
A Python array is a data structure that can hold multiple values of the same type, like integers or floats.
Unlike Python lists (which can hold mixed data types), arrays in Python’s array module are type-restricted and more memory-efficient.
🔧 How to Create an Array
First, you need to import the array module:
import array
# Syntax: array.array(typecode, [elements])
numbers = array.array('i', [1, 2, 3, 4])
📌 i stands for integer. Other type codes include:
'f'– float'd'– double'u'– Unicode character
🔍 Accessing Array Elements
print(numbers[0]) # Output: 1
print(numbers[2]) # Output: 3
✅ Indexing starts at 0, just like lists.
🔄 Loop Through an Array
for num in numbers:
print(num)
🎯 Efficient for reading or processing all values.
🛠️ Modify Array Elements
numbers[1] = 10
print(numbers) # Output: array('i', [1, 10, 3, 4])
➕ Add Items to an Array
Append a single element:
numbers.append(5)
Insert at specific position:
numbers.insert(2, 99) # Insert 99 at index 2
➖ Remove Items from an Array
Remove by value:
numbers.remove(10)
Remove last item:
numbers.pop()
🧮 Array Methods You Should Know
| Method | Purpose |
|---|---|
.append(x) | Add item to end |
.insert(i, x) | Insert at index |
.remove(x) | Remove first occurrence |
.pop() | Remove last item |
.index(x) | Find index of value |
.reverse() | Reverse the array |
.buffer_info() | Memory address and size info |
.typecode | Shows the type of array elements |
⚠️ Array vs List in Python
| Feature | Array (array module) | List |
|---|---|---|
| Data type | Same type only | Mixed types allowed |
| Memory usage | More efficient | Less efficient |
| Speed | Faster (for numbers) | Slower (for numbers) |
| Use case | Numeric data | General-purpose |
🧠 Real-Life Use Case
Let’s say you’re building a temperature tracking system. You can use an array to efficiently store hourly temperature readings:
import array
temps = array.array('f', [30.2, 31.4, 29.8, 33.5])
Great for working with large datasets or sending numerical data to low-level systems.
🏁 Final Thoughts
While Python lists are versatile, the array module is ideal when you need performance and memory optimization for large numeric datasets.
Understanding arrays helps you work closer to the hardware level and makes you a more well-rounded Python developer.
📘 Learn more Python basics, data structures, and memory-efficient techniques at TechTown.in

