How to declare and add items to an array in Python?

To declare an array in Python, you can use the array module. Here is an example of how to create an array of integers:

import array

my_array = array.array('i', [1, 2, 3, 4, 5])

print(my_array)

The first argument to the array() function is the type code for the elements of the array. In this case, 'i' stands for integers. The second argument is a list of the initial elements of the array.

Watch a course Python - The Practical Guide

You can also use the built-in list type to create an array, like this:

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

To add an item to the array, you can use the append() method or the += operator. Here is an example of adding the number 6 to the array:

my_array.append(6)

or

my_array += [6]

You can also use the extend() method to add multiple items to the array at once:

my_array.extend([7, 8, 9])

You can insert an element at a particular index using the insert() method as follows:

my_array.insert(2,10)

This will insert the element 10 at the index 2.