Working with arrays in python¶
array is one of the sequence types in the python. Python arrays behave mostly same like lists except array
only stores the homogeneous data type(i.e same data type either integer, string, etc).
Defining a python array¶
- To define the python array we have define the type of the data
- Let's define the array of type numbers
from array import array
numbers = array('i', [1,2,3,4,5])
print(numbers)
# output: array('i', [1, 2, 3, 4, 5])
Avalable types in arrays¶
We have the following types available for arrays in python
Type code | C Type | Python Type | Minimum size in bytes |
---|---|---|---|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | Py_UNICODE | Unicode character | 2 |
'h' | signed short | int | 2 |
'H' | unsigned short | int | 2 |
'i' | signed int | int | 2 |
'I' | unsigned int | int | 2 |
'l' | signed long | int | 4 |
'L' | unsigned long | int | 4 |
'q' | signed long long | int | 8 |
'Q' | unsigned long long | int | 8 |
'f' | float | float | 4 |
'd' | double | float | 8 |
why to arrays instead lists in python?¶
- We should use it when you need to expose a C array to an extension or a system call (for example,
ioctl
orfctnl
). - Arrays are more efficient than lists for some uses. If you need to allocate an array that you know will not change, then arrays can be faster and use less memory.
- On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.
methods of python arrays¶
Most of the arrays methods are similar to the python lists.
append
: To add the elements in the end of an array.insert
: To add the elements at an index position.count
: Return the number of occurrences of x in the array.extend
: Append items from iterable to the end of the arrayindex
: Return the smallest i such that i is the index of the first occurrence of x in the array.pop
: Removes the item with the index i from the array and returns it.remove
: Remove the first occurrence of x from the array.reverse
: Reverse the order of the items in the array.tolist
: Convert the array to an ordinary list with the same items.
Reference: https://docs.python.org/3/library/array.html