Using Freshworks apps? Check out what we can do for you! Learn More

TechAffinity Rwanda at GITEX Africa: Africa’s Premier Global Technology Community Learn More


How to Create, Access, Slice, Change, Delete & Search Python Arrays?


Before getting into Python ArraysPython ArraysAn array is a data structure that stores values of same data type. In Python, this is the main difference between arrays and lists. While python lists can contain values corresponding to different data types, arrays in python can only contain values corresponding to same data type. and its data structure, let’s see what exactly are arrays. An array is a data structure that contains a homogenous group of elements. These elements are either integers or strings. Arrays are commonly used in programming languages to organize data so that a related set of values can be easily sorted or searched. 

PythonPythonWith dynamic semantics, Python is an object-oriented, interpreted, high-level programming language. Python reduces the maintenance cost of the program as it has simple and easy to learn syntax that emphasizes readability. Thanks to its high-level built-in data structures for making it attractive for Rapid Application Development, as well as for using it as a scripting language. Python supports a wide range of libraries and a few of them are numpy, pandas, matpotlib, scipy, etc. doesn’t come with built-in data structures out of the box like most of the other programming languages such as C++C++C++ is a high-level programming language, C++ adds object-oriented features to its predecessor, C. C++ is one of the most popular programming language for graphical applications, such as those that run in Windows and Macintosh environments., JavaScriptJavaScriptJavaScript, often abbreviated as JS, is a high-level, interpreted scripting language that conforms to the ECMAScript specification. JavaScript has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions., and JavaJavaJava is one of the majorly used general-purpose programming language designed to have no or limited implementation dependencies. Java requires a software platform for its compiled programs to be executed. Oracle and Android SDK are a few examples of the software platforms on which Java executes its programs.. But, Python does have lists, and with the help of an array module, it supports arrays of numeric values.

/* Use Jupyter’s “Classic Notebook“ for accurate output */

Python Arrays

Remember to use the elements of the same type while creating arrays in Python using the array module. Else, your code will result in errors. Below is an example for better understanding.

x = [50, 100, 150] is valid


x = [50, 100, 150,”TechAffinity”] is not valid & result in error

Creating Arrays

Whenever you want to use arrays in Python, the first step is always to import the array module.

import array as cr7
x = cr7.array('f', [3, 5, 7, 9])
print (x)

array(‘f’, [3.0, 5.0, 7.0, 9.0])

There are some “Type Codes” that determine the type of array during creation. In the above example, the letter ‘f’ is a type code that determines the type of array. Here’s a simple example:

‘b’ – signed char

‘B’ – unsigned char

‘d’ – double

‘f’ – float

‘i’ – signed int

‘I’ – unsigned int

‘h’ – signed short

‘H’ – unsigned short

‘l’ – signed long

‘L’ – unsigned long

Accessing Array Elements

To access an element, you can go ahead with indices just like lists. Python arrays also start from 0. Here’s a simple example:

import array as cr7
x = cr7.array ('i', [25, 50, 75, 100])
print("The first element of the array:", x[0])
print("The second element of the array:", x[1])
print("The last element of the array:", x[3])

The first element of the array: 25
The second element of the array: 50
The last element of the array: 100

Slicing Arrays

“:” is the slicing operator in Python and with the help of this operator, a range of elements present in an array can be sliced. Here’s a simple example:

import array as cr7
example_list = [10, 20, 30, 40, 50, 60, 70, 80]
example_array = cr7.array('i', example_list)
print(example_array[2:5]) #third to fifth
print(example_array[:-5]) #beginning to forth
print(example_array[5:]) #sixth to end
print(example_array[:]) #beginning to end

array(‘i’, [30, 40, 50])
array(‘i’, [10, 20, 30])
array(‘i’, [60, 70, 80])
array(‘i’, [10, 20, 30, 40, 50, 60, 70, 80])

Changing or Adding Elements

Similar to the lists, you can easily change the elements in an array. It is so because arrays in Python are mutable in the Python programming language. Here’s an example to illustrate it better. Here’s a simple example:

import array as cr7
millions = cr7.array('i', [5, 10, 15, 20, 25, 30])
millions[0] = 1 #replacing the first element 5 with 1
millions[1:3] = cr7.array('i', [5, 10]) #changing second and third elements

array(‘i’, [1, 10, 15, 20, 25, 30])
array(‘i’, [1, 5, 10, 20, 25, 30])

Using the array method “append()”, you can easily add an extra element at the end of an array. Similarly, the array method “extend()” method enables the addition of multiple elements. Here’s a simple example:

import array as cr7
millions = cr7.array('i', [2, 4, 6])
millions.append(8) #includes 8 as the last element to the array
millions.extend([10, 12, 14, 16, 18])

array(‘i’, [2, 4, 6, 8])
array(‘i’, [2, 4, 6, 8, 10, 12, 14, 16, 18])

“+” is the concatenation operator and is used to concatenate two arrays. Here’s a simple example:

import array as cr7
prevyear = cr7.array('i', [2, 8, 12, 14])
curyear = cr7.array('i', [16, 20, 24, 30])
millions = cr7.array('i') #creates an empty array of integer
millions = prevyear + curyear

array(‘i’, [2, 8, 12, 14, 16, 20, 24, 30])

Deleting Elements from an Array

You can easily remove elements from an array, or entirely delete the array using the del statement. Here’s a simple example:

import array as cr7
millions = cr7.array('i', [2, 6, 12, 24, 72])
del millions[3] #removes the fourth element
del millions #deletes the entire array

array(‘i’, [2, 6, 12, 72])
NameError: name ‘millions’ is not defined

Further, to facilitate deleting/removing the elements from an array, Python array methods “remove()” and “pop()” can be used. The “remove()” method is used to remove a specific element from the declared array; whereas, the “pop()” method is used to remove a specific element and printing it. Here’s a simple example:

import array as cr7
squares = cr7.array('i', [4, 9, 16, 25, 36, 49, 64, 81])

array(‘i’, [4, 9, 16, 25, 36, 64, 81])
array(‘i’, [4, 9, 16, 25, 36, 64])

Searching an Element in Array

In Python programming language, you can search for an element based on the index or value of the element. The array method “index()” helps you to find an element based on its value. When you use the array method “index()”, the program will return you the index of the element you searched for. Here’s a simple example:

import array as cr7
cubes = cr7.array('i', [8, 27, 64, 125, 216, 343])
print (cubes.index(64)) #returns the index of the element 64
print(cubes.index(30)) #returns a value error as there is no element with value 30

ValueError: array.index(x): x not in list

When the program couldn’t find the index of your given value, it returns a value error as shown in the above illustration.

Python Array Methods

Given below are various built-in methods used in Python for using arrays:

  • append() – Adds an element at the end of the array list
  • reverse() – Reverses the order of an array list
  • clear() – Eliminates all elements from the array list
  • pop() – Removes an element from the specified position
  • count() – Returns the elements along with their total number
  • insert() – Adds an element to the specified position in the array list
  • copy() – Returns a copy of the array list
  • extend() – Add the elements of an array list to the end of the current list
  • remove() – Eliminates the first element with the specified value
  • index() – Returns the index of the first element in an array list with the specified value
  • sort() – Sorts the array list

Though the lists in Python are more flexible, can store elements of different data types and are faster, arrays in Python play a key role when there comes a need to interface with the “C” programming language. Moreover, when you want to play around with matrices, you can go the extra mile with the Python arrays and array methods.

We, at TechAffinity, have a host of Python developers having hands-on experience in working on Python lists, Python arrays, and more. Our experts can offer more simplified solutions to your complex business needs. Line up your queries to or schedule a meeting to further discuss the same.

Also Read: Java vs Python

Subscribe to Our Blog

Stay updated with latest news, updates from us