Python Add Item To Array

What we are going to see through this article is we will see in detail about Python Add Item To Array. If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List.

  • Lists or append(),
  • Extend(),
  • Insert().

In addition to, We can use two methods to do a task here. Those are:

  • Array Module,
  • NumPy Array Module.
Python Add Item To Array

Python Add Item to Array using lists or append()

my_input = ['English', 'Hindi'] 
my_input.append('Tamil') 
print(my_input) 

Output

This is the output.

['English', 'Hindi', 'Tamil']

Python Add Item to Array using extend() function

Below, We have to use the extend() function to execute a task here.

my_input = ['English', 'Hindi'] 
input1 = [50, 40, 30, 20, 10] 
my_input.extend(input1) 
print(my_input)

Output

This is the output.

['English', 'Hindi', 50, 40, 30, 20, 10]

Python Add Item to 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

This is the output.

Current Numbers List [1, 2, 3, 4, 5]

Please enter the number to be added:
10

Enter the index between 0 and 4 to add the given number:
2

Updated List [1, 2, 10, 3, 4, 5]

Process finished with exit code 0

Python Add Item to Array Using Array Module

We can use the array module to add elements to the array in the below program.

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

This is an example output for your reference.

array('i', [1, 2, 3])
array('i', [4, 5, 6])
array('i', [1, 2, 3, 4, 5, 6])
array('i', [1, 2, 3, 4])
array('i', [10, 1, 2, 3, 4])
array('i', [10, 1, 2, 3, 4, 4, 5, 6])

Python Add Item to Array Using NumPy Array

import numpy
 # insert function
arr1_insert = numpy.array([1, 24, 34])
  
arr2_insert = numpy.insert(arr1_insert, 1, 81)
  
print(arr2_insert)
# append function
arr1_append = numpy.array([8, 4, 2])
  
arr2_append = numpy.append (arr1_append, [15, 16, 17])
  
print(arr2_append)

Read Also: Check If A Number Is Positive Or Negative Using C++

Output

The output will be given below:

[ 1 81 24 34]
[ 8 4 2 15 16 17]

Final Thoughts

What we learned through this article is Python Add Item To Array. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment