Which array method in Python is used to add an element to the end of the array?

Which array method in Python is used to add an element to the end of the array?

a) append()
b) insert()
c) extend()
d) push()

Answer:

a) append()

Explanation:

The .append() method in Python is used to add a single element to the end of an array. This method modifies the original array by adding the new element to the end of the sequence.

from array import array
numbers = array('i', [1, 2, 3])
numbers.append(4)
print(numbers)  # Outputs array('i', [1, 2, 3, 4])

The .append() method is useful when you need to dynamically add elements to an array without having to create a new array or manually manage indices.

Using the .append() method simplifies the process of adding elements to arrays, making your code more efficient and easier to maintain.

Leave a Comment

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

Scroll to Top