Array operations in Python

In Python, arrays are collections of elements of the same type stored in contiguous memory locations. Using Python's array module, you can perform various operations on arrays such as adding, updating, deleting elements, and more. Arrays offer a way to efficiently handle fixed data types, unlike lists which can hold different types of elements.

Imagine organizing a bookshelf by genre. In Python, arrays allow you to organize data similarly, grouping similar items in contiguous memory locations.

What is an array?

An array is a collection of elements of the same type that are stored at contiguous memory locations. Arrays are sequence types that behave very much like lists except that the type of objects stored in them is constrained. The idea is to store multiple items of the same type together.

We can treat lists like arrays; however, we cannot constrain the type of elements stored in a list.

Python array
Python array

Let's see a list example where elements are of the different types:

python_list = [2, 5.5, "Hai"]
print (python_list)

Arrays in Python can be created by importing an array module.

Creating an array

Array creation in Python follows the following syntax:

import array as ar
new_array = ar.array(data_type, value_list)

array(data_type, value_list) is used to create an array with data type and value list specified in its arguments.

import array as ar
new_arr = ar.array('d', [2, 5.5, "Hai"])
print(new_arr)

The above code will throw an error since the elements in the array are of different data types.

Following are the different types of arrays in Python:

Datatype Value
d Represents floating-point of size 8 bytes
b Represents signed integer of size 1 byte
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
B Represents unsigned integer of size 1 byte
c Represents character of size 1 byte
f Represents floating-point of size 4 bytes

Let’s now see a floating-point array example:

import array as ar
new_arr = ar.array('d', [2.1, 4.5, 5.5])
print(new_arr)

How to access array elements in Python

We can access each element of an array using the index of the element.

Slicing Python arrays

We can access a range of items in an array by using the slicing operator:

Index positions and indices of a Python array
Index positions and indices of a Python array

Python also has what you could call its "inverse index positions." Using this, you can read an array in reverse.

For example, if you use the index -1, you will be interacting with the last element in the array.

Knowing this, you can easily access each element of an array by using its index number.

For instance, if we wanted to access the number 16 in our array, all we need to do is use our variable (called with square brackets, []) and the index position of the element.

Let's understand this with the help of an example. The below code shows how we can access elements.

import array as ar
new_arr = ar.array('d', [2.1, 4.5,3.5,4.2,3.3, 5.5])
print("First element:", new_arr[0])
print("Second element:", new_arr[1])
print("Last element:", new_arr[-1])
print("Slicing array elements in a range: 3-5.\n", new_arr[2:5])
print("Elements sliced from 3rd element to the end.\n",new_arr[3:])
print("Printing all elements using slice operation.\n", new_arr[:])

Try experimenting with the code.

Here, consider altering the slicing indices in the example above to see different subsets of the array.

Different array operations

Let’s explore some different array operations such as finding the length of the array changing array elements, adding elements to an array etc.

Length of the array

Use the len() method to return the length of an array (the number of elements in an array).

import array as ar
new_arr = ar.array('b', [1,2,4,7,9,33])
a = len(new_arr)
print(a)

Updating array elements

Arrays are mutable—their elements can be changed in a similar way as lists.

import array as ar
new_arr = ar.array('i', [1, 2, 3, 5, 7, 10])
new_arr[0] = 0
print(new_arr)

Try updating any element with a character or a string and see how the code responds.

Adding elements to an array

We can add one item to the array using the append() method, or add several items using the extend() method.

import array as ar
new_arr = ar.array('i', [1, 2, 3])
new_arr.append(4)
print(new_arr)
new_arr.extend([5, 6, 7])
print(new_arr)

Below is an example where all different operations are being performed on the same array:

import array as ar
new_arr = ar.array('i', [1, 2, 3])
ln=len(new_arr)
print(ln) #length
new_arr[0] = 0 #changing first element
print(new_arr)
new_arr.append(4) #appending 4 to array
print(new_arr)
new_arr.extend([5, 6, 7]) #extending numbers with 5,6,7
print(new_arr)

Adding new elements to the array

Insert operation is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of the built-in array.insert() function in Python.

import array as ar
new_arr = ar.array('i', [1, 2, 3, 5, 7, 10])
new_arr.insert(1,9)
for x in new_arr:
print(x)

Deleting elements from an array

Deletion refers to removing an existing element from the array and re-organizing all elements of an array. The built-in remove() method is there in Python.

import array as ar
new_arr = ar.array('i', [1, 2, 3, 5, 7, 10])
new_arr.remove(7)
for x in new_arr:
print(x)

Try it yourself

Exercise: Array management

Practice adding, updating, and removing elements in an array using Python's array module.

Instructions

  1. Create an array:

    1. Initialize an array of integers with the following elements: [10,20,30,40,50][10, 20, 30, 40, 50].

  2. Add elements to the array:

    1. Append the number 6060 to the end of the array.

    2. Insert the number 2525 at index 22.

  3. Update elements in the array:

    1. Change the element at index 33 from 4040 to 4545.

    2. Modify the first element of the array to 1515.

  4. Remove an element from the array:

    1. Remove the element 5050 from the array.

  5. Print the final array:

    1. Display the final state of the array after all operations.

Expected output

Initial array: array('i', [10, 20, 30, 40, 50])
After appending 60: array('i', [10, 20, 30, 40, 50, 60])
After inserting 25 at index 2: array('i', [10, 20, 25, 30, 40, 50, 60])
After updating index 3 to 45: array('i', [10, 20, 25, 45, 40, 50, 60])
After updating first element to 15: array('i', [15, 20, 25, 45, 40, 50, 60])
After removing 30: array('i', [15, 20, 25, 45, 40, 60])
Final array: array('i', [15, 20, 25, 45, 40, 60])
# Write your code here

You can refer to the given "Solution" on pressing the "Run" button if you are stuck.
Make sure to give it your best first!

Searching an element

To search an element in an array, there're are two methods:

  • Using the in keyword

  • Using index() method

The in keyword

We can use the in keyword to check if an element exists in the array.

import array as ar
my_array = ar.array('i', [10, 20, 30, 40, 50])
# Check if an element exists
element = 30
if element in my_array:
print(element, "found in the array.")
else:
print(element, "not found in the array.")

The index() method

We can use the index() method to get the index of the element in the array. If the element is not found, it raises a ValueError.

import array as ar
my_array = ar.array('i', [10, 20, 30, 40, 50])
try:
index = my_array.index(30)
print("Element found at index", index)
except ValueError:
print("Element not found in the array.")

Take a minute and think what should be the output of the above code before clicking the "Run" button!

Also, try altering the code by changing the values to get a better understanding.

Reverse an array

To reverse an array in Python we have several approaches. Here’s how we can reverse an array efficiently:

Using [::-1] slicing

We can reverse an array using Python's slicing feature, which is simple and concise.

import array as ar
new_arr = ar.array('i', [1, 2, 3, 2, 7, 10,2])
# Reverse the array using slicing
reversed_array = new_arr[::-1]
print("Reversed array:", reversed_array)

Using reverse() method

The reverse() method reverses the array in place.

import array as ar
my_arr = ar.array('i', [1, 2, 3, 2, 7, 10,2])
# Reverse the array in place
my_arr.reverse()
print("Reversed array:", my_arr)

Counting elements in the array

The count() method is used to get the number of occurrences in the array.

array.count(x) returns the number of occurrences of x in the array.

import array as ar
new_arr = ar.array('i', [1, 2, 3, 2, 7, 10,2])
occurrence_of_x = 2
print(new_arr.count(occurrence_of_x))

Key takeaways

  1. Arrays vs. lists: Arrays contain elements of a single type, while lists can hold elements of mixed types.

  2. Array creation: Arrays in Python are created using the array module with the syntax array(data_type, value_list).

  3. Array operations: Python arrays support multiple operations such as accessing elements by index, slicing, appending, inserting, updating, and deleting elements.

  4. Reversing an array: You can reverse an array in place using the reverse() method or create a reversed copy using slicing ([::-1]).

  5. Array methods: Common methods include append(), extend(), insert(), remove(), count(), and index() for element operations.

  6. Efficient storage: Arrays offer more efficient memory usage compared to lists when working with large data of the same type.

If you're eager to deepen your understanding of Python and sharpen your problem-solving skills, our Become a Python Developer path is the perfect next step. With this structured path, you'll go beyond fundamental concepts and dive into advanced topics that will prepare you for a successful career in software engineering.

Don’t just learn Python—become proficient and ready for the challenges of the real world.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between arrays and lists in Python?

Arrays store only elements of the same type, while lists can contain elements of different types.


What is the difference between append() and extend() in arrays?

append() adds a single element, while extend() adds multiple elements from a list or another array.


What happens if you try to create an array with mixed data types?

Python will raise an error since arrays require all elements to be of the same data type.


What are the performance implications of using arrays versus lists, and when should I choose one over the other in Python projects?

Arrays (from Python’s array module) are more memory-efficient and faster for numeric data, making them ideal for projects with large datasets of numbers. Lists, however, are more flexible, supporting mixed data types, so they’re better suited for general-purpose use cases requiring versatility.


Free Resources