CodesCompiler
🔍
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact 🚀 Get Started Free

PYTHON - Add Array Items

Python - Add Array Items

Python array is a mutable sequence which means they can be changed or modified whenever required. However, items of same data type can be added to an array. In the similar way, you can only join two arrays of the same data type.

Python does not have built-in support for arrays, it usesarray moduleto achieve the functionality like an array.

Adding Elements to Python Array

There are multiple ways to add elements to an array in Python −

  • Using append() method
  • Using insert() method
  • Using extend() method

Using append() method

To add a new element to anarray, use theappend()method. It accepts a single item as an argument and append it at the end of given array.

Syntax

Syntax of the append() method is as follows −

PYTHON CODE
append(v)

Where,

  • v− new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.

Example

Here, we are adding element at the end of specified array using append() method.

PYTHON CODE
import array as arr
a = arr.array('i', [1, 2, 3])
a.append(10)
print (a)

It will produce the followingoutput−

PYTHON CODE
array('i', [1, 2, 3, 10])

Using insert() method

It is possible to add a new element at the specified index using theinsert()method. The array module in Python defines this method. It accepts two parameters which are index and value and returns a new array after adding the specified value.

Syntax

Syntax of this method is shown below −

PYTHON CODE
insert(i, v)

Where,

  • i− The index at which new value is to be inserted.
  • v− The value to be inserted. Must be of the arraytype.

Example

The following example shows how to add array elements at specific index with the help of insert() method.

PYTHON CODE
import array as arr
a = arr.array('i', [1, 2, 3])
a.insert(1,20)
print (a)

It will produce the followingoutput−

PYTHON CODE
array('i', [1, 20, 2, 3])

Using extend() method

Theextend()method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.

Syntax

This method has the following syntax −

PYTHON CODE
extend(x)

Where,

  • x− This parameter specifies an array or iterable.

Example

In this example, we are adding items from another array to the specified array.

PYTHON CODE
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5])
b = arr.array('i', [6,7,8,9,10])
a.extend(b)
print (a)

On executing the above code, it will produce the followingoutput−

PYTHON CODE
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])