add element to an array in python

To add an element to an array in Python, we have two methods:

  1. Append method:

To add an element to the end of an array, we can use the append() method. Here is an example:

main.py
array = [1, 2, 3, 4]
array.append(5)
print(array) # output: [1, 2, 3, 4, 5]
76 chars
4 lines
  1. Insert method:

To add an element at a specific index in an array, we can use the insert() method. Here is an example:

main.py
array = [1, 2, 3, 4]
array.insert(2, 5)
print(array) # output: [1, 2, 5, 3, 4]
79 chars
4 lines

In the example above, the insert() method inserts the element 5 at index 2 in the array. The first argument of the insert() method is the index where we want to add the element and the second argument is the element itself that we want to add to the array.

gistlibby LogSnag