Learn Programming through LIVE online classrooms

Python and Data Structures and Algorithms

A Comprehensive Guide to Python Arrays

Posted in Python, Data Structures and Algorithms

In programming, an array is a homogenous (belonging to the same data type) collection of elements. Unlike languages like C++, Java, and JavaScript, arrays aren’t among the built-in Python data structures.

Although Python doesn’t have built-in support for arrays, that doesn’t stop programmers from implementing them.

Python Arrays

As a replacement to arrays, Python has lists. Nonetheless, Python supports arrays of numeric values using the array module.

When creating arrays using the array module in Python, remember that all elements of the array must be of the same type. If this is not the case then an error will be produced. For instance,

a = [1, 22, 240] is valid

but

a = [1, 22, 240, “Akhil”] is not valid and will thus, yield an error

Creating Arrays

Before declaring arrays, it is required to import the array module. For instance, take a look at the following code snippet:

import array as ar1
a = ar1.array(‘d’, [1.2, 2.2, 2.4, 4.6])
print (a)

Output:

array(‘d’, [1.2, 2.2, 2.4, 4.6])

We’ve created an array of float type after importing the array module. The letter ‘d’ is a type code that determines the type of array during creation. Following are some of the most important array type codes in Python:

  • ‘b’ – signed char
  • ‘B’ – unsigned char
  • ‘d’ – double
  • ‘f’ – float
  • ‘h’ – signed short
  • ‘H’ – unsigned short
  • ‘i’ – signed int
  • ‘I’ – unsigned int
  • ‘l’ – signed long
  • ‘L’ – unsigned long

Accessing Array Elements

Indices are used for accessing elements of an array in Python. Like lists, the index starts from 0. For example:

import array as ar1
a = ar1.array (‘i’, [22, 24, 46, 53])
print(“The first element of the array:”, a[0])
print(“The second element of the array:”, a[1])
print(“The last element of the array:”, a[2])

Output:

The first element of the array: 22

The second element of the array: 24

The last element of the array: 53

Slicing Arrays

By using the slicing operator (:), it is possible to access a range of elements present in an array in Python programming language. Following code snippet demonstrates using the slicing operator with an array in Python:

import array as ar1
number_list = [2, 4, 22, 25, 24, 52, 46, 5]
number_array = ar1.array('i', number_list)
print(numbers_array[2:5]) # third to fifth
print(numbers_array[:-5]) # beginning to forth
print(numbers_array[5:]) # sixth to end
print(numbers_array[:]) # beginning to end

Output:

array(‘i’, [22, 25, 24])

array(‘i’, [2, 4, 22, 25])

array(‘i’, [46, 5])

array(‘i’, [2, 4, 22, 25, 24, 52, 46, 5])

Adding or Changing Elements

Arrays are mutable. Hence, their elements can be changed in a similar way as lists. Consider the following code sample:

import array as ar1
numbers = ar1.array('i', [1, 2, 3, 4, 6, 10])
numbers[0] = 0 # replacing the first element 1 with 0
print(numbers)
numbers[2:5] = arr.array('i', [4, 6, 8]) # changing third, fourth, and fifth elements
print(numbers)

Output:

array('i', [0, 2, 3, 4, 6, 10])

array('i', [0, 2, 4, 6, 8, 10])

The append() method is used for adding one element to an array while the extend() method allows adding multiple elements. These new elements are added to the end of the array. Observe the following code snippet:

import array as ar1
numbers = ar1.array('i', [1, 2, 3])
numbers.append(4) # adds 4 to the array at the last position
print(numbers)
numbers.extend([5, 6, 7]) # appends iterable to the end of the array
print(numbers)

Output:

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

array('i', [1, 2, 3, 4, 5, 6, 7])

The concatenation operator (+) is used for concatenating two arrays in Python programming language. For example:

import array as ar1
odd = ar1.array('i', [11, 33, 55])
even = ar1.array('i', [22, 44, 66])
numbers = ar1.array('i') # creates an empty array of integer
numbers = odd + even
print(numbers)

Output:

array(‘i’, [11, 22, 33, 44, 55, 66])

Deleting Elements from an Array

The del statement can be used for removing one or more elements from an array in Python. For instance:

import array as ar1
number = ar1.array('i', [11, 22, 33, 33, 44])
del number[2] # removes the third element
print(number)
del number # deletes the entire array
print(number)

Output:

array('i', [11, 22, 33, 44])

Error: array is not defined

While the remove() method can be used for removing a specific element from the array, the pop() method allows for removing a specific element and display it. Use of both these methods are illustrated in the following code snippet:

import array as ar1
numbers = ar1.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers)
print(numbers.pop(2))
print(numbers)

Output:

array('i', [10, 11, 12, 13])

12

array('i', [10, 11, 13])

Searching an Element in Array

Based on the index or value of the element, it is possible to search for the same in an array. The index() method is used for searching an element in an array based on its value. The method returns the index of the element being searched. For instance:

import array as ar1
numbers = ar1.array('i', [10,20,30,40,50])
print (array1.index(40)) # returns the index of the element 40

Output:

3

In case there is no such element that is being searched in an array, the program will give out an error.

Array Methods

These are the various inbuilt methods in Python for using with arrays:

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

Conclusion

Although knowing how to deal with arrays isn’t a mandatory part of learning Python, able to do so is surely an added advantage. This is especially true when dealing with churning out arrays and matrices. Nonetheless, lists in Python are way much more flexible than arrays.

Unlike arrays, lists are able to store elements belonging to different data types and are faster. Typically, the array module is required for interfacing with C code. It is typically advised to avoid using arrays in Python. However, that doesn’t mean that you can’t learn them.

Check out these best 10 Python books to help you through and make your Python learning better and more insightful.

Shruti Kaushik

Shruti Kaushik

Shruti is a professionally accredited content specialist and works closely with brands to identify their disconnect in content marketing, then further strategizing the same. She started pursuing her independent journey as a consultant after leaving her decent 9 to 5 job with Google News as an editor, and have worked withSony, Ministry of Skills and Entrepreneurship Ma Foi Group, TOI, Indochine International, Kakaku, Inc in the past. View all posts by the Author

Leave a comment

Your email will not be published
Cancel
Adam
Adam 0 Points

numbers = ar1.array('i', [1[10,20,30,40,50]

I'm just learning python, but that looks bad syntax. Why no closing brackets for the initial ( and [ in the numbers array?

Shiv kumar
Shiv kumar

Very nice Blog we will definitely try for our website. Thank you for sharing.

Ravi Kumar
Ravi Kumar 10 Points

Thanks for sharing a blog on python if you want to enhance your skills then you can join Data Science Training Course