How to Append an Array in Python?

The array is an important data structure in Python that can store a large collection of data of the same data type. Lists are also similar to arrays, but we can store data of different types in the list. 

We can perform various operations on the array using different Python functions such as adding, removing, appending, etc. The “append()” method is used to append an array in Python. 

This post will address possible methods to append an array in Python:

How to Append an Array in Python?

The “append()” function is used in Python to append an array. The following examples demonstrate how we can achieve that in Python:

Example 1: Using append() Function to Append an Array

In the code given below, the “append()” function is used to append a float value with the input array.

Code: 

import array
array_value = array.array('d', [5.5, 2.4])
value1 = 5.5
array_value.append(value1)
print(array_value)

In the above code:

  • A function named “array.array()” is used to generate a new array.
  • The “array.array()” function takes a type code or data type of the array as a first argument, and the “list” is passed as a second argument. 
  • The “append()” function takes the float value as an argument and appends the value to the given array.

Output:

The above output shows that the “5.5” has been successfully appended to the input array.

Example 2: Using append() Function to Append a Numpy Array

In the code given below, the “append()” function is used along with the “np.arange()” function to append the two numpy arrays:

Code:

import numpy
array1 = numpy.arange(5)
array2 = numpy.arange(16,20)
output = numpy.append(array1, array2)
print(output)

In the above code:

  • The “numpy.arange()” function creates the range of the array by taking the interval value.
  • The “numpy.append()” function accepts the two arrays as arguments, appends the given arrays, and returns a new array.

Output:

The array “[0 1 2 3 4]” has been appended to array “[16 17 18 19]”.

Example 3: Using append() Function to Append a Dynamic Array (Lists)

A dynamic array or list can also be appended into another list using the “append()” function. The below code demonstrates this example:

Code:

list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']
list1.append(list2)
print(list1)

In the above code:

  • The two list values named “list1” and “list2” are initialized in the program.
  • The “append()” function takes the “list2” as an argument and appends it to “list1”.

Output:

The list1 has been appended to list2.

Conclusion

In Python, the “append()” method is used to append an array. The “array” module, ”np.arange()” method and dynamic array (List) are used to create an array in Python. The “array.array()” function creates an array by accepting the type code and byte object (initializer) as a parameter.  This guide provides a detailed guide on appending an array in Python using multiple examples.