Python Arrays

🐍 Python Arrays

In Python, arrays can be implemented in two ways:

  1. Using lists (most common, flexible)

  2. Using the array module (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 float

  • Common 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

  1. Create a list of 10 numbers and find their sum.

  2. Create an array of integers using the array module and remove an element.

  3. Create a 3×3 matrix using nested lists and print the diagonal elements.

  4. Using NumPy, create an array of 5 numbers and multiply each by 10.

  5. Loop through a list and print only even numbers.

You may also like...