Python Arrays
🐍 Python Arrays
In Python, arrays can be implemented in two ways:
Using lists (most common, flexible)
Using the
arraymodule (more like traditional arrays, type-specific)
1. Using Python Lists as Arrays
Python lists can store multiple elements of different data types:
Lists are dynamic — you can add or remove elements.
Lists support slicing, indexing, loops.
List Operations
2. Using the array Module
If you want a true array with same data type elements, use the array module.
'i'→ type code for signed integer'f'→ type code for floatCommon type codes:
| Type | Code |
|---|---|
| int | 'i' |
| float | 'f' |
| double | 'd' |
| char | 'u' |
Array Operations
3. Accessing Array Elements
Works for lists and array.array.
4. Looping Through Arrays
5. Multidimensional Arrays
Using Nested Lists
Using numpy (Recommended for large arrays)
6. Array Operations with NumPy
7. Summary
| Feature | List | array module | NumPy Array |
|---|---|---|---|
| Type-specific | ❌ No | ✅ Yes | ✅ Yes |
| Dynamic Size | ✅ Yes | ✅ Yes | ✅ Yes |
| Supports Loops | ✅ Yes | ✅ Yes | ✅ Yes |
| Mathematical Operations | ❌ No | Limited | ✅ Yes |
🧠 Practice Exercises
Create a list of 10 numbers and find their sum.
Create an array of integers using the
arraymodule and remove an element.Create a 3×3 matrix using nested lists and print the diagonal elements.
Using NumPy, create an array of 5 numbers and multiply each by 10.
Loop through a list and print only even numbers.
