In programming terms, an array is a linear data structure that stores similar kinds of elements. Array data type does not exist in Python. Instead, you can use a Python list or numpy array.
The list is similar to an array in other programming languages. If you look at the list as an array, then to append an item to the array, use the list append() method.
To create an array in Python, use one of the following ways.
- Python list
- Python array using array module.
- Python numpy array
Python array append
To append an item in the array in Python, use the list append() method. The append() method appends an element to the end of the list.
Syntax
list.append(element)
Parameters
The append() function takes an element as a parameter and returns the appended list.
Return Value
The method doesn’t return any value and None.
Example
list = ["Wonder Woman 84", "Suicide Squad", "Tom and Jerry"] print(list) print("After appending a new element") list.append("Friends") print(list)
Output
['Wonder Woman 84', 'Suicide Squad', 'Tom and Jerry'] After appending a new element ['Wonder Woman 84', 'Suicide Squad', 'Tom and Jerry', 'Friends']
Python array module
We can create an array using the Array module and then apply the append() function to add elements to it. To work with the array module, import the array module.
To initialize an array using the array module in Python, use the array.array() method.
array.array('unicode', elements)
unicode: It represents the type of elements to be occupied by the array. For example, ‘i’ represents integer elements.
To append an item in the array, use the array.append() method.
import array data = array.array('i', [11, 21]) d2 = 19 data.append(d2) print(data)
Output
array('i', [11, 21, 19])
The array append() method added an element at the end of the array.
Numpy array append in Python.
Python numpy append() method appends values to the end of an array. A Numpy module can be used to create an array and manipulate the data against various mathematical functions.
We will create two arrays using the np.arange() function and append two arrays.
import numpy as np k1 = np.arange(4) print("First array : ", k1) k2 = np.arange(4, 9) print("Second array : ", k2) op = np.append(k1, k2) print("\nResult after appending k1 and k2: ", op)
Output
First array : [0 1 2 3] Second array : [4 5 6 7 8] Result after appending k1 and k2: [0 1 2 3 4 5 6 7 8]
In this example, we got the result of the combined array of k1 and k2.