W3docs

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

To declare an array in Python, you can use the array module.

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

declare and add items to an array in Python

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. Common type codes also include 'f' for floats and 'd' for double-precision floats. The second argument is a list of the initial elements of the array.

Note that Python's standard dynamic sequence is actually the built-in list type, which is more commonly used than the array module. You can create a list like this:

Use python lists instead of arrays

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

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

Append an element to a Python list using the append method

my_list.append(6)

or

Append an element to a Python list using the += operator

my_list += [6]

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

Append multiple elements to a Python list using the extend method

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

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

Insert an element at a specific index using the insert method

my_list.insert(2, 10)

This will insert the element 10 at index 2.