Google News
logo
Python Program to Add an element to an array
In the following example of Python program You can use the `append()` method to add an element to the end of an array :
Program :
my_array = [1, 2, 3, 4, 5]
my_array.append(6)
print(my_array)
Output :
[1, 2, 3, 4, 5, 6]
Alternatively, you can use the `insert()` method to add an element at a specified index. Here's an example:
Program :
my_array = [1, 2, 3, 4, 5]
my_array.insert(2, 'new_element')
print(my_array)
Output :
[1, 2, 'new_element', 3, 4, 5]
In this example, the string `'new_element'` is inserted at index `2` (i.e., between the second and third elements) of the array.