Python Array

Python is a popular programming language used for developing applications in various domains. One of the most used data structures in Python is the array. An array is a collection of elements of the same type that are stored in contiguous memory locations. In this blog, we will learn about Python arrays and how to use them with some examples.

Creating an array in Python To create an array in Python, we need to import the array module. The array() function takes two arguments – the type of elements in the array and the initial values.

Let’s create an array of integers with the initial values 1, 2, 3, and 4.

import array as arr

a = arr.array('i', [1, 2, 3, 4])
print("Array a:", a)

Output:

Array a: array('i', [1, 2, 3, 4])

In the code above, we imported the array module using the alias ‘arr’. We created an array of integers using the array() function, specifying the type ‘i’ for integer and the initial values [1, 2, 3, 4]. Finally, we printed the array a.

Accessing elements in an array We can access the elements in an array using their index. The index of the first element is 0, and the index of the last element is the length of the array minus one.

Let’s access the elements in the array a we created earlier.

print("First element:", a[0])
print("Last element:", a[-1])

Output:

First element: 1
Last element: 4

In the code above, we accessed the first element of the array using the index 0 and the last element using the index -1.

Inserting elements in an array We can insert elements in an array using the insert() function. The insert() function takes two arguments – the index where we want to insert the element and the element we want to insert.

Let’s insert the element 5 at index 2 in the array a.

a.insert(2, 5)
print("Array a:", a)

Output:

Array a: array('i', [1, 2, 5, 3, 4])

In the code above, we inserted the element 5 at index 2 in the array a using the insert() function.

Removing elements from an array We can remove elements from an array using the remove() function. The remove() function takes the element we want to remove as an argument.

Let’s remove the element 3 from the array a.

a.remove(3)
print("Array a:", a)

Output:

Array a: array('i', [1, 2, 5, 4])

In the code above, we removed the element 3 from the array a using the remove() function.

Conclusion In this blog, we learned about Python arrays and how to create, access, insert, and remove elements in an array using example code snippets. Arrays are a useful data structure in Python for storing a collection of elements of the same type. We can perform various operations on arrays using built-in functions in Python.