Forum

Learn Python Arrays
 
Notifications
Clear all

Learn Python Arrays

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

Python has a few ways to work with arrays, depending on what you’re trying to do. Let’s break it down 🧠🐍


🧺 1. Using Lists as Arrays

Python’s built-in lists are the most common way to store sequences of items.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
  • Lists can hold mixed data types.
  • They’re dynamic, so you can add/remove items easily.
  • You can loop through them, slice them, and use tons of built-in methods.

🧪 2. Using the array Module

If you want a more memory-efficient array with only one data type, use the array module.

import array as arr

numbers = arr.array('i', [1, 2, 3, 4])  # 'i' stands for integer
numbers.append(5)
print(numbers)
  • Type codes like 'i' (int), 'f' (float) define the data type.
  • Great for large numeric datasets when memory matters.

🔬 3. Using NumPy Arrays

For scientific computing or multi-dimensional arrays, NumPy is the go-to.

import numpy as np

a = np.array([1, 2, 3])
print(a * 2)  # Output: [2 4 6]
  • Supports multi-dimensional arrays (like matrices).
  • Super fast and efficient for math-heavy operations.
  • Ideal for data science, machine learning, and simulations.

🧠 Quick Comparison

Feature List array Module NumPy Array
Mixed types ✅ Yes ❌ No ❌ No
Memory efficient ❌ No ✅ Yes ✅ Yes
Math operations ❌ Limited ❌ Limited ✅ Powerful
Multi-dimensional ❌ No ❌ No ✅ Yes

 


   
Quote
Share: