This comprehensive Python Array tutorial explains what is an Array in Python, its syntax, and how to perform various operations like sort, traverse, delete, etc:
Consider a bucket containing the same items in it such as brushes or shoes, etc. The same goes for an array. An array is a container that can hold a collection of data of the same type.
Therefore all the elements in an array have to be all integers or all floats etc. This makes it easier to calculate the position where each element is located or to perform a common operation that is supported by all entries.
Arrays are mostly used when we want to store data of a particular type or when we want to constrain the data type of our collection.
=> Visit Here To Learn Python From Scratch
What You Will Learn:
- Python Arrays
- Array Syntax
- Python Built-in Array Module
- Array Type Codes
- Array Basic Operations
- #1) Traversing an Array
- #2) Inserting into an Array
- Modify or Updating an Array Element in an Index
- Deleting an Element From an Array
- Searching an Array
- Other Arrays Methods and Properties
- Frequently Asked Questions
Arrays are handled by a Python object-type module array. Arrays behave like lists except for the fact that the objects they contain are constrained by their types and most importantly, they are faster and use lesser memory space.
In this tutorial, we will study the Python array under the following topics:
- Array syntax
- Python built-in array module
- Array type code
- Array Basic Operations: Traverse, Insertion, Deletion, Search, Update.
- Other Array Methods
An array can be diagnosed as such:
- Elements: Are items stored in the array.
- Index: Represents the location where an element is stored in an array.
- Length: Is the size of the array or the number of indexes the array possesses.
- Indices: Is the index map of the array value stored in the object.
The above figure displays an array with a length of 6, and the elements of the array are [5, 6, 7, 2, 3, 5]. The index of the array always begins with 0(zero-based) for the first element, then 1 for the next element, and so on. They are used to access the elements in an array.
As we have noticed, we can treat arrays as Lists but cannot constrain the data type in a list as it is done in an array. This will be understood much more in the next section.
Python Built-in Array Module
There are many other built-in modules in Python which you can read more about from here. A module is a Python file containing Python definitions and statements or functions. These statements are used by calling them from the module when the module is imported into another Python file. The module used for the array is called an array.
The array module in Python defines an object that is represented in an array. This object contains basic data types such as integers, floating points, and characters. Using the array module, an array can be initialized using the following syntax.
arrayName = array.array(dataType, [array items])
Let’s understand its various parts with the labeled diagram below
Example 1: Printing an array of values with type code, int.
>>> import array # import array module >>> myarray = array.array('i',[5,6,7,2,3,5]) >>> myarray array('i', [5, 6, 7, 2, 3, 5])
The above example is explained below;
- The name arrayName is just like naming any other variable. It can be anything that abides by Python naming conversions, in this case, myarray.
- The first array in array.array is the module name that defines the array() class. It must be imported before used. The first line of code does just that.
- The second array in array.array is the class called from the array module which initializes the array. This method takes two parameters.
- The first parameter is dataType which specifies the data type used by the array. In example 1, we used the data type ‘i’ which stands for signed int.
- The second parameter used by the array method specifies the elements of the array provided as an iterable like list, tuple. In example 1 a list of integers was provided.
Array Type Codes
The array type code is the data type(dataType) which must be the first parameter of the array method. This defines the data code which constraints elements in the array. They are represented in the below table.
Table 1: Array Type codes
|Type Code||Python type||C Type||Minimum size in bytes|
|‘q’||int||Signed long long||8|
|‘Q’||int||Unsigned long long||8|
The array module defines a property called .typecodes that returns a string containing all supported type codes found in Table 1. While the array method defines the typecode property which returns the type code character used to create the array.
Example 2: Get all array’s supported type codes and type code used to define an array.
>>> import array >>> array.typecodes # get all type codes. 'bBuhHiIlLqQfd' >>> a = array.array('i',[8,9,3,4]) # initialising array a >>> b = array.array('d', [2.3,3.5,6.2]) #initialising array b >>> a.typecode #getting the type Code, 'i', signed int. 'i' >>> b.typecode #getting the type Code, 'd', double float 'd'
Array Basic Operations
In the sections above, we saw how to create an array. In this section, we shall examine a couple of operations that can be performed on its object. To summarize, these operations are Traverse, Insertion, Deletion, Search, Update.
#1) Traversing an Array
Just like lists, we can access elements of an array by indexing, slicing and looping.
An array element can be accessed by indexing, similar to a list i.e. by using the location where that element is stored in the array. The index is enclosed within square brackets [ ], the first element is at index 0, next at index 1 and so on.
N.B: An array index must be an integer.
Example 3: Access elements of an array by indexing.
>>> from array import array # import array class from array module >>> a = array('i', [4,5,6,7]) # create an array of signed int. >>> a # access at index 0, first element 4 >>> a # access at index 3, 4th element 7 >>> a[-1] # access at index -1, last element, same as a[len(a)-1] 7 >>> a # access at index 9, out of range Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: array index out of range
Negative indexing starts counting backward i.e. an index of -1 will return the last item in the array.
Also, just like a list, providing an index that doesn’t exist will return an IndexError exception indicating an out-of-range attempt.
Just like lists, we can access elements of an array using the slicing operator [start : stop : stride]
To know more about slicing and how it applies to strings, check out the tutorial Python String Operators and Methods.
Example 4: Access elements of an array by slicing.
>>> from array import array # import array class from array module >>> a = array('f', [4,3,6,33,2,8,0]) # create array of floats >>> a array('f', [4.0, 3.0, 6.0, 33.0, 2.0, 8.0, 0.0]) >>> a[0:4] # slice from index 0 to index 3 array('f', [4.0, 3.0, 6.0, 33.0]) >>> a[2:4] # slice from index 2 to index 3 array('f', [6.0, 33.0]) >>> a[::2] # slice from start to end while skipping every second element array('f', [4.0, 6.0, 2.0, 0.0]) >>> a[::-1] # slice from start to end in reverse order array('f', [0.0, 8.0, 2.0, 33.0, 6.0, 3.0, 4.0])
Looping an array is done using the for loop. This can be combined with slicing as we saw earlier or with built-in methods like enumerate().
Example 5: Access elements of array by looping.
from array import array # import array class from array module # define array of floats a = array('f', [4,3,6,33,2,8,0]) # Normal looping print("Normal looping") for i in a: print(i) # Loop with slicing print("Loop with slicing") for i in a[3:]: print(i) # Loop with method enumerate() print("loop with method enumerate() and slicing") for i in enumerate(a[1::2]): print(i)
#2) Inserting into an Array
Insertion in an array can be done in many ways.
The most common ways are:
Using insert() Method
The same goes for a List – an array uses its method insert(i, x) to add one to many elements in an array at a particular index.
The insert function takes 2 parameters:
- i: Position where you want to add in the array. As mentioned before, the negative index will start counting from the end of the array.
- x: The element you wish to add.
NB: Adding an element to an occupied position or index, will shift all elements starting from that index to right, then insert the new element at that index.
Example 6: Add to an array using the insert() method.
>>> from array import array # importing array from array module >>> a= array('i',[4,5,6,7]) # initialising array >>> a.insert(1,2) # inserting element: 2 at index: 1 >>> a # Printing array a array('i', [4, 2, 5, 6, 7]) >>> a.insert(-1,0) # insert element: 0 at index: -1 >>> a array('i', [4, 2, 5, 6, 0, 7]) >>> len(a) # check array size 6 >>> a.insert(8, -1) # insert element: 0 at index: 8, this is out of range >>> a array('i', [4, 2, 5, 6, 0, 7, -1])
NB: If the index is out of range, then this won’t raise an exception. Instead, the new element will be added at the end of the array without causing a shift to the right as seen before. Check the last insertion in the Example 6 above.
Using append() method
This method can also be used to add an element to an array but this element will be added at the end of the array with no shift to the right. It is same as example 6 where we used the insert() method with an out of range index.
Example 7: Add to an array using the append() method.
>>> from array import array >>> a= array('i',[4,5,6,7]) # initialising array >>> a.append(2) # appending 2 at last index >>> a array('i', [4, 5, 6, 7, 2])
Using and Slicing
As we shall see below, slicing is commonly used to update an array. However, based on the indexes provided to the slicing, insertion can take place instead.
Note that, with slicing, we must add another array.
Example 8: Add into an array using slicing.
>>> from array import array >>> a = array('i',[2,5]) # create our array >>> a[2:3] = array('i',[0,0]) # insert a new array >>> a array('i', [2, 5, 0, 0])
From the above example, we should note these few things.
- In order to perform an insertion, the slicing should start at an index which is out of range. It doesn’t matter what index it is.
- The new element to be added should come from another array.
Using extend() method
This method appends items from iterable to the end of the array. It may be any iterable as long as its elements are of the same type as the array we are to append to.
Example 9: Add into an array using extend()
>>> from array import array >>> a = array('i',[2,5]) >>> a.extend([0,0]) #extend with a list >>> a array('i', [2, 5, 0, 0]) >>> a.extend((-1,-1)) # extend with a tuple >>> a array('i', [2, 5, 0, 0, -1, -1]) >>> a.extend(array('i',[-2,-2])) # extend with an array >>> a array('i', [2, 5, 0, 0, -1, -1, -2, -2])
Using fromlist() Method
This method appends items from a list at the end of the array. It is equivalent to a.extend([x1,x2,..]) and also for x in list: a.append(x).
Note that for this to work, all the items in the list should be of the same type code as the array.
Example 10: Add into an array using fromlist()
>>> from array import array >>> a = array('i',[2,5]) >>> a.fromlist([0,0]) #insert from list >>> a array('i', [2, 5, 0, 0])
Modify or Updating an Array Element in an Index
We can update an array’s element by using indexing. Indexing allows us to modify a single element and unlike insert(), it raises an IndexError exception if the index is out of range.
Example 11: Modify an array’s element at a specific index.
>>> from array import array >>> a = array('i', [4,5,6,7]) >>> a = 9 # add element: 9 at index: 1 >>> a array('i', [4, 9, 6, 7]) >>> len(a) # check array size 4 >>> a = 0 # add at index: 8, out of range Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: array assignment index out of range
Deleting an Element From an Array
We have two array methods that can be used to remove an element from an array. These methods are the remove() and pop().
This method removes the first occurrence of an element, x, in an array but returns an ValueError exception if the element does not exist. After the element is deleted the function re-arranges the array.
Example 12: Remove an element using the remove() method
>>> from array import array array('i', [3, 4, 6, 6, 4]) >>> a.remove(4) # remove element: 4, first occurrence removed. >>> a array('i', [3, 6, 6, 4])
Pop( [ i ] )
This method on the other hand deletes an element from an array by using it’s index, i , and returns the element popped from the array. If no index is provided, pop() removes the last element in an array.
Example 13: Remove an element using the pop() method
>>> from array import array >>> a= array('i',[4,5,6,7]) >>> a.pop() # remove and return last element, same as a.pop(len(a)-1) 7 >>> a array('i', [4, 5, 6]) >>> a.pop(1) # remove and return element at index: 1 5 >>> a array('i', [4,6]
N.B: The difference between pop() and remove() is that the former removes and returns an element at an index while the latter removes the first occurrence of an element.
Searching an Array
Array allows us to search it’s elements. It provides a method called index(x). This method takes in an element, x, and returns the index of the first occurrence of the element.
Example 14: Find the index of an element in an array with index()
>>> from array import array >>> a = array('d', [2.3, 3.3, 4.5, 3.6]) >>> a.index(3.3) # find index of element: 3.3 1 >>> a.index(1) # find index of element: 1, not in array Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: array.index(x): x not in array
From the example above, we notice that searching an element that doesn’t exist in the array raises an ValueError exception. Hence, this operation is often called in a try-except exception handler.
Example 15: Use try-except block to handle exception in index()
from array import array a = array('d', [2.3, 3.3, 4.5, 3.6]) try: print(a.index(3.3)) print(a.index(1)) except ValueError as e: print(e)
Other Arrays Methods and Properties
The Array class has many methods and properties to help us manipulate and get more information about its elements. In this section, we shall look at the commonly used methods.
This method takes in an element as an argument and counts the occurrence of an element in the array.
Example 16: Count the occurrence of an element in an array.
>>> from array import array >>> a = array('i', [4,3,4,5,7,4,1]) >>> a.count(4) 3
This method reverses the order of elements in an array in place. This operation modifies the array because in Python an array is mutable i.e. can be changed after created.
Example 17: Reverse the order of items in an array.
>>> from array import array >>> a = array('i', [4,3,4,5,7,4,1]) >>> a.reverse() >>> a array('i', [1, 4, 7, 5, 4, 3, 4])
This array’s property returns the length in bytes of one array element in the array’s internal representation.
>>> from array import array >>> a = array('i', [4,3,4,5,7,4,1]) >>> a.itemsize 4 >>> a.itemsize * len(a) # length in bytes for all items 28
As this only returns the length in bytes of one array item, in order to get the size of the memory buffer in bytes, we can compute it like the last line of the above code.
Frequently Asked Questions
Q #1) How to declare an array in Python?
Answer: There are 2 ways in which you can declare an array either with the array.array() from the built-in array module or with the numpy.array() from numpy module.
With array.array(), you just need to import the array module and then declare the array subsequently with a specified type code, while with the numpy.array() you will need to install the numpy module.
Q #2) What is the difference between Array and List in Python?
Answer: The major difference between Array and List in Python is that the former only consists of elements of the same type while the latter can consist of elements of different types.
Q #3) How do we add elements into an array in Python?
Answer: Elements can be added into an array in many ways. The most common way is using the insert(index, element) method, where index indicates the position where we will like to insert and element is the item to insert.
However, we have other ways such as using the methods append(), extend(). We can also add by slicing the array. Check the sections above to know more about these methods.
Q #4) How do we get all the type codes available in the Python array?
Answer: The Python official documentation contains all type codes and more details about them. Also, we could get these type codes from the terminal by using the code.
>>> import array >>> array.typecodes 'bBuhHiIlLqQfd'
From the output above, each letter in the returned string represents a type code. More precisely, here are the various Python types.
‘b’ = int
‘B’ = int
In this tutorial, we looked at the Python array which is a built-in module.
We also looked at Array’s basic operations such as Traverse, Insertion, Deletion, Search, Update. Lastly, we looked at some of the commonly used Array methods and properties.
=> Explore The Simple Python Training Series Here