Insert & append methods – Add elements in Array – Python

Arrays in Python are homogeneous, type-code specific, memory optimized and indexed based sequential data structure. Array module provides insert() and append() methods to add elements in an array. We will explore the base logic to add elements in an array.

Insert elements in Array

Array module in Python provides insert() method to add given element at the given index. Syntax for the insert() method:

array_object.insert(index, element)

  • array_object is an array (specific to type-code) in which we want to add an element at a given index.
  • insert is the name of the method
  • index is the index position at which element to be added. After adding new element at given index, existing elements will move towards right.
  • element is the element to be added. This element should be of the same type-code with which array_object was created. Otherwise we will get an OverflowError or TypeError.
  • This method does not return any value (return None).
  • Array with new element will be referenced with the original array object array_object.

Add element – insert() method

# array of integer type - insert method - insert integer
print("array of integer type - insert method - insert integer")

import array as array   # import array module

integer_array = array.array("i", [10, 20, 30, 40])   # declare and initialized array, type-code for integer
print(integer_array)

integer_array.insert(3, 50)   # add element at an index
print(integer_array)

In this program, first we are importing the array module. We are declaring and initializing an array with type-code i (integer). This array is referenced by variable integer_array. We are using integer_array.insert(3, 50) to add element 50 at index position 3. Initially 40 was at index 3, after inserting new element 50 will be at index 3 and 40 will move to index 4.

Program Output

array of integer type - insert method - insert integer
array('i', [10, 20, 30, 40])    # original array - initially defined
array('i', [10, 20, 30, 50, 40])  # element 50 added at index 3, 40 moved to index 4

In the similar way, we can add elements using insert() method for other type-codes like:

  • b (signed char), B (unsigned char)
  • h (signed short), H (unsigned short)
  • i (signed integer), I (unsigned integer)
  • l (signed long), L (unsigned long)
  • q (signed long long), Q (unsigned long long)
  • f (float), d (double)
  • u (Unicode)

TypeError – insert() method

An array can have elements only of the defined type-code. Element to add with insert() method should be of same type-code with which original array was created. Otherwise we will get an OverflowError or TypeError.

# TypeError - insert float with unsigned short type-code
print("TypeError - insert float with unsigned short type-code")

import array as array      # import array module

unsigned_short_array = array.array("H", [10, 20, 30, 40])  # declare and initialized array, type-code unsigned short
unsigned_short_array.insert(3, 50.55)  # add float element

In this scenario, we have import the array module. We are declaring and initializing an array with type-code H (unsigned-short). This array is referenced by variable unsigned_short_array. Using unsigned_short_array.insert(3, 50.55) we are adding a float number into this array. This will throw an TypeError because original array was declared with type-code H (unsigned-short).

Program Output

TypeError - insert float with unsigned short type-code
Traceback (most recent call last):
  File "D:\insert-element-array .py", line 16, in <module>
    unsigned_short_array.insert(3, 50.55)
TypeError: 'float' object cannot be interpreted as an integer

From the program output, we got an error => TypeError: ‘float’ object cannot be interpreted as an integer.

Custom implementation – insert() method

Arrays are generally of fixed size. New elements can be added by creating another array of increased size and copying all the elements of existing array into the new array. We will see the custom implementation logic to add elements at given position.

# custom implementation - insert() method
print("custom implementation - insert() method")

import array as array   # import array module

def custom_insert(array_object, index, element):   # method with three arguments
    if index < 0:
        index = len(array_object) + index

    new_array_object = array.array(array_object.typecode, [0] * (len(array_object) + 1))
    for x in range(len(new_array_object)):
        if x < index:
            new_array_object[x] = array_object[x]
        elif x == index:
            new_array_object[x] = element
        else:
            new_array_object[x] = array_object[x - 1]
    return new_array_object

signed_long_array = array.array("l", [135, 28976, 323674, 499834])
signed_long_array = custom_insert(signed_long_array, -3, 5055)
print(signed_long_array)

Lets understand the step by step implementation of this program.

  • We are importing array module. This is to read the original array object and to create the new array object.
  • We are defining a method custom_insert(array_object, index, element), this method will take three arguments array_object => original array object in which new element to be added, index position on which new element to be added, element to be added
  • If negative index is given, then convert it to positive index scenario. This is required for common logic to added element.
  • Crew a new array new_array_object of same type-code and of extra length.
  • Using for loop and range() method, iterate through the index positions of an array.
  • Add logic (if, elif, else conditions) to update elements in the new array based on index position.
  • Return the new array object with new element added at given index position.
  • Assign reference to this returned object with signed_long_array (same variable which was referring to old array object).
  • Print the value of the new array with added element at given index position.
  • For example => we are passing an array with type-code l (signed long) and add element 5055 at index -3 (positive index 1).

Program Output

custom implementation - insert() method
array('l', [135, 5055, 28976, 323674, 499834])

From the program output, new element 5055 added at index -3, which is position index 1.

Append elements in Array

Array module in Python provides append() method to add element at the end of an array. Syntax for the append() method:

array_object.append(element)

  • array_object is an array (specific to type-code) in which we want to add an element at the end of array.
  • append is the name of the method
  • element is the element to be added at the end of an array. This element should be of the same type-code with which array_object was created. Otherwise we will get an OverflowError or TypeError.
  • This method does not return any value (return None).
  • Array with new element will be referenced with the original array object array_object.

Add element – append() method

# array of double type - append method - append double
print("array of double type - append method - append double")

import array as array    # import array module

double_array = array.array("d", [13.43, 25.67, 32.54, 40.76])   # declare and initialized array, type-code for double
print(double_array)

double_array.append(58.76)  # add element at the end of array
print(double_array)

In this program, first we are importing the array module. We are declaring and initializing an array with type-code d (double). This array is referenced by variable double_array. We are using double_array.append(58.76) to add element 58.76. Using append() method, element will be added at the end of an array.

Program Output

array of double type - append method - append double
array('d', [13.43, 25.67, 32.54, 40.76])    # original array - initially defined
array('d', [13.43, 25.67, 32.54, 40.76, 58.76])   # element 58.76 added at end of an array

In the similar way, we can using append() method elements can be added at the end of an array. Element type-code and array type-code should be same. Other type-codes that can be used are:

  • b (signed char), B (unsigned char)
  • h (signed short), H (unsigned short)
  • i (signed integer), I (unsigned integer)
  • l (signed long), L (unsigned long)
  • q (signed long long), Q (unsigned long long)
  • f (float), d (double)
  • u (Unicode)

OverflowError – append() method

An array can have elements only of the defined type-code. Element to add with append() method should be of same type-code with which original array was created. Otherwise we will get an OverflowError or TypeError.

# array of unsigned short type - append method - append signed short
print("array of unsigned short type - append method - append signed short")

import array as array  # import array module

unsigned_short_array = array.array("H", [1, 2, 3, 4])  # declare and initialized array, type-code unsigned short
print(unsigned_short_array)

unsigned_short_array.append(-5)   # add signed short element

In this scenario, we have import the array module. We are declaring and initializing an array with type-code H (unsigned-short). This array is referenced by variable unsigned_short_array. Using unsigned_short_array.append(-5) we are adding a signed short number into this array. This will throw an OverflowError because original array was declared with type-code H (unsigned-short).

Program Output

array of unsigned short type - append method - append signed short
array('H', [1, 2, 3, 4])
Traceback (most recent call last):
  File "D:\append-element-array.py", line 50, in <module>
    unsigned_short_array.append(-5)
OverflowError: unsigned short is less than minimum

From the program output, we got an error => OverflowError: unsigned short is less than minimum.

Custom implementation – append() method

Arrays are generally of fixed size. New elements can be added by creating another array object of increased size and copying all the elements of existing array into the new array. We will see the custom implementation logic to add elements at the end of an array.

# custom implementation - append() method
print("custom implementation - append() method")

import array as array    # import array module

def custom_append(array_object, element):   # method with two arguments

	new_array_object = array.array(array_object.typecode, [0] * (len(array_object) + 1))
	for x in range(len(array_object)):
		new_array_object[x] = array_object[x]

	new_array_object[len(array_object)] = element
	return new_array_object


signed_long_array = array.array("l", [135, 28976, -323674, -499834])
signed_long_array = custom_append(signed_long_array, 5055)
print(signed_long_array)

Lets understand the step by step implementation of this program.

  • We are importing array module. This is to read the original array object and to create the new array object.
  • We are defining a method custom_append(array_object, element), this method will take two arguments array_object => original array object in which new element to be added, element to be added
  • Crew a new array new_array_object of same type-code and of extra length. Using array_object.typecode, type-code value is taken from array_object itself.
  • Using for loop and range() method, iterate through the index positions of an array.
  • Add logic to update elements in the new array based on index position.
  • Finally, add the element at the end of the new array
  • Return the new array object with new element added at the end of it.
  • Assign reference to this returned object with signed_long_array (same variable which was referring to old array object).
  • Print the value of the new array with added element at given index position.
  • For example => we are passing an array with type-code l (signed long) and add element 5055 at the end of array.

Program Output

custom implementation - append() method
array('l', [135, 28976, -323674, -499834, 5055])

From the program output, new element 5055 added at the end of array.

Summary

In this article we learned about insert() and append() method to add element into the given array. We explored various scenarios with type-codes, TypeError and OverflowError. Following topics were discussed:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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