T
Tech Town
Log InSign Up Free
← Back to Blog

June 19, 2025 · admin

Python Arrays


๐Ÿ“š 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

MethodPurpose
.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
.typecodeShows the type of array elements

โš ๏ธ Array vs List in Python

FeatureArray (array module)List
Data typeSame type onlyMixed types allowed
Memory usageMore efficientLess efficient
SpeedFaster (for numbers)Slower (for numbers)
Use caseNumeric dataGeneral-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