Python array methods are functions available for manipulating arrays created using the array module, which stores homogeneous data types efficiently. These methods allow you to add, remove, search, and modify elements in an array.
Core Array Methods
append(x): Adds an elementxto the end of the array.extend(iterable): Appends all elements from an iterable (e.g., list, tuple) to the end of the array.insert(i, x): Inserts elementxat indexi.remove(x): Removes the first occurrence of elementx.pop([i]): Removes and returns the element at indexi(or the last element if no index is specified).index(x[, start[, stop]]): Returns the index of the first occurrence ofxwithin the specified range.count(x): Returns the number of timesxappears in the array.
Utility and Conversion Methods
reverse(): Reverses the order of elements in the array.tolist(): Converts the array to a standard Python list.fromlist(list): Appends elements from a list to the array.tobytes(): Returns the array's contents as a bytes object.frombytes(buffer): Appends items from a bytes-like object to the array.fromfile(f, n): Readsnitems from file objectfand appends them.tofile(f): Writes all items to file objectf.
Important Notes
Arrays in Python are homogeneous—all elements must be of the same type, defined by a type code (e.g.,
'i'for integers,'f'for floats).The
arraymodule is distinct from standard lists, which are more flexible but less memory-efficient.For numerical computing, NumPy arrays are preferred, offering additional methods like
.sum(),.mean(),.reshape(), and.sort().
💡 Example:
import array arr = array.array('i', [1, 2, 3]) arr.append(4) arr.insert(1, 5) print(arr.tolist()) # Output: [1, 5, 2, 3, 4]
Python arrays
What is Python's list.append() method WORST Time Complexity? It can't be O(1), right?
__getitem__ method in 2D array class.
Is it bad practice to over rely on arrays / lists (JS/python)
Videos
I'm following roadmap.sh/python to learn python. I'm at the DSA section.
I understand the concept of arrays in DSA, but what I don't understand is how to represent them in Python.
Some tutorials I've seen use lists to represent arrays (even though arrays are homogeneous and lists are heterogeneous).
I've seen some other tutorials use the arrays module to create arrays like array.array('i') where the array has only integers. But I have never seen anybody use this module to represent arrays.
I've also seen some tutorials use numpy arrays. Which I don't understand their difference from the normal arrays module.
What should I use to represent arrays?
So far I've solved a couple of arrays exercises using Python lists.