Python add elements to an Array

Python doesn’t have a specific data type to represent arrays.

The following can be used to represent arrays in Python:


1. Adding to an array using Lists

If we are using List as an array, the following methods can be used to add elements to it:

  • By using append() function: It adds elements to the end of the array.
  • By using insert() function: It inserts the elements at the given index.
  • By using extend() function: It elongates the list by appending elements from both the lists.

Example 1: Adding elements to an array using append() function

my_input = ['Engineering', 'Medical'] 
my_input.append('Science') 
print(my_input) 

Output:

['Engineering', 'Medical', 'Science']

Example 2: Adding elements to an array using extend() function

my_input = ['Engineering', 'Medical'] 
input1 = [40, 30, 20, 10] 
my_input.extend(input1) 
print(my_input)

Output:

['Engineering', 'Medical', 40, 30, 20, 10]

Example 3: Adding elements to an array using insert() function

my_input = [1, 2, 3, 4, 5]

print(f'Current Numbers List {my_input}')

number = int(input("Please enter a number to be added:\n"))

index = int(input(f'Enter the index between 0 and {len(my_input) - 1} to add the given number:\n'))

my_input.insert(index, number)

print(f'Updated List {my_input}')

Output:

Output Insert Function
Output-Insert Function

2. Adding to an array using array module

If we are using the array module, the following methods can be used to add elements to it:

  • By using + operator: The resultant array is a combination of elements from both the arrays.
  • By using append() function: It adds elements to the end of the array.
  • By using insert() function: It inserts the elements at the given index.
  • By using extend() function: It elongates the list by appending elements from both the lists.

Example:

import array

s1 = array.array('i', [1, 2, 3])
s2 = array.array('i', [4, 5, 6])

print(s1)  
print(s2)  

s3 = s1 + s2
print(s3)  

s1.append(4)
print(s1)  

s1.insert(0, 10)
print(s1) 

s1.extend(s2)
print(s1) 

Output:

Output Array Module
Output Array Module

3. Addition of elements to NumPy array

We can add elements to a NumPy array using the following methods:

  • By using append() function: It adds the elements to the end of the array.
  • By using insert() function: It adds elements at the given index in an array.

Example:

import numpy
 # insert function
arr1_insert = numpy.array([1, 23, 33])
 
arr2_insert = numpy.insert(arr1_insert, 1, 91)
 
print(arr2_insert)
# append function
arr1_append = numpy.array([4, 2, 1])
 
arr2_append = numpy.append (arr1_append, [12, 13, 14])
 
print(arr2_append)

Output:

[ 1 91 23 33]
[ 4 2 1 12 13 14]


Conclusion

Thus, in this article, we have implemented possible ways to add elements to an array.


References