How to Append to Array in Python

Python append to array

In python, we have three implementations of the array data structure. In this article, we will discuss those array implementations. After that, see how we can append elements to the different array implementations in python. 

What are the Different Array Implementations in Python?

We can implement arrays using three different approaches namely lists, array module, and NumPy module in python. Let us discuss them one by one.

Python Lists

Python lists are the most generic implementation of array data structure in python. We can store objects with different data types in a single list. To create a list with given elements, we can use the list() constructor. The list() constructor accepts a collection of elements as input argument and returns a list object with all the given elements as shown in the following example.

Output:

Here, we have provided a tuple containing 10 numbers as an input argument to the list() constructor. After execution, it has returned a list object that is assigned to the myList variable.

Instead of using the list() constructor, you can use the square brackets [ ] to create a list using the given elements if you have individual elements instead of a collection object. You can observe this in the following example.

Output:

Here, we have created a list using the square brackets and individual elements instead of a collection object.

We can also create a list using the elements of other container objects such as a set or a tuple. For this, we just need to pass the container object to the list() constructor as follows.

Output:

In the above example, we have created a list using the elements of a set by giving the set object as an input argument to the list() constructor.

Lists are container objects and they can also contain other container objects along with other elements as shown below.

Output:

Here, we have created a list that contains a set within it. Hence, a list can also contain other container objects.

Python Arrays

You can see that there are no restrictions on the data types of the elements in a list. However, python provides us with the arrays module to create arrays with a specific data type. You can install the arrays module using PIP as follows.

In python3, you can download the arrays module as follows.

To create an array using the arrays module, we use the array() constructor. The array() constructor takes a character denoting the data type of the elements of the array and the elements of the array in a list as the second input argument. For character codes for the different data types, you can refer to the official documentation for the arrays module.  Upon execution, it returns an array with the elements of the specified data types as follows.

Output:

Here, we have specified the first input argument as “i” to denote that the elements in the array are signed integers. Similarly, we can specify “f” for floating-point values, “d” for double values, “b” for signed characters, etc. After execution, the array() function returns an array object.

If the input list in the second input argument to the array() constructor contains elements with the data types other than that specified in the first input argument, it raises the TypeError exception as follows.

Output:

Here, when we tried to include a string in an integer array, the program ran into TypeError exception and showed the message “TypeError: an integer is required (got type str)

Also, we cannot add other container objects to the arrays in python.

Output:

Here, we have tried to insert a set in an integer array. Again, the program runs into the TypeError exception and shows the message “TypeError: an integer is required (got type set)

Python Numpy Arrays

NumPy arrays are multidimensional arrays. We can also use NumPy arrays as one-dimensional arrays by defining 2-dimensional arrays of shape Nx1 where N is the number of columns i.e. elements in the 1-D array and 1 denotes that the multidimensional array has only one row. 

To create a NumPy array, we can use the array() constructor. The array() constructor takes a collection of elements as its first argument and returns an object of type ndarray as follows.

Output:

Here, you can observe that we have created an array of type numpy.ndarray with 10 elements. You can also observe that we have simply passed a list to the array() function and haven’t specified the data type for the elements.

If we do not specify the data type of elements in the NumPy array, we can create an array of elements of different data types as follows.

Output:

Here, we have created a NumPy array with integers and strings as its elements.

You can also specify the data type of the elements explicitly using the “dtype” parameter. The default value for the “dtype” parameter is “None”. When we don’t specify the data type of the elements of the array to be created, the array() function automatically recognizes the datatype of the elements in the input. Otherwise, we can specify the data type of the elements as follows.

Output:

Here, we have specified the data type of the elements as integer data type by providing the argument "i” to the dtype parameter.

Here, you have to make sure that the elements of the collection object are of the same data type or at least compatible data types like int and float. In the case of incompatible data types, the array() constructor raises the ValueError exception as follows.

Output:

In the above example, we have specified the data type of the elements of the array to be the integer type. However, the list that has been passed to the array() function contains a string in it. Hence, the program runs into the ValueError exception showing the message ValueError: invalid literal for int() with base 10: 'java2blog'.

Having discussed the implementation of different types of arrays in python, let us discuss how we can append elements to an array in python.

Append Element to List in python

You can append elements to a list in python using the append() method. The append() method, when invoked on a list, takes the element to be appended as the input argument and appends the element at the end of the list as shown below.

Output:

You can observe that the new element is appended to the original list. Hence, it is modified. You can append elements of any data type or collection objects to the list using the append() method as follows.

Output:

Here, we have appended an integer, a set, and a string into a list originally containing integers. So, we can say that we can append any object to a list in python.

Append to array in Python

To append an element to an array, we can use the append() method as we did in the case of the lists. Here, The append() method accepts an element as an input argument and appends it to the end of the list as follows.

Output:

The difference between the append() method for array objects and the append() method for lists is that you can only provide elements of the specified data type to the append() method when it is invoked on an array. The data type of the input argument should be that of the elements already present in the array. Otherwise, the append() method will raise the TypeError exception as follows.

Output:

Here, we have tried to append a string to an array containing integers. Due to this, the program has run into the TypeError exception showing the message “TypeError: an integer is required (got type str)

Append to NumPy array in python

To append an element to a NumPy array, we can use the append() method defined in the NumPy module. The append() method defined in the NumPy module takes the array as the first input argument, the value to be appended to the array as the second input argument, and an optional argument axis as its third argument. The parameter axis has a default value 0. Upon execution, it returns a new array that has the input values appended to the input array. You can observe this in the following example.

Output:

The append() method returns a new array and the original array in which the values are appended doesn’t get modified. You can verify this by simply printing the array before and after the append operation.

Output:

If we do not specify the data type of the elements while creating the NumPy array, we can append the element of any data type into the array.

Output:

Here, you can observe that we haven’t specified the data type of the array elements while creating the array. Hence, we are able to append an element of any data type to the array.

If we specify the data type of elements while creating the NumPy array, these arrays also have restrictions on the data types of the elements. However, when we append an element to the NumPy array, a new array is created. The new array can contain elements of any data type. We can say that we can append the element to the array using the append() method. However, in reality, a new array is created having elements of the original array and the element to be appended. So, the elements are not appended to the original array.

Output:

Conclusion

In this article, we have discussed different types of arrays in python. We also discussed how we can append elements to an array in python using the various array implementations. 

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *