Python Array

Beginner’s & Experience Developers Python Array Tutorial: Array is a popular topic in most the programming languages like C/C++, JavaScript, Python, etc. By performing the arrays you can find many advantages while programming. In this tutorial, we are going to discuss completely Arrays in Python. Python arrays are often misinterpreted as lists or NumPy Arrays. Let’s go through this python array beginner’s tutorial and explore what is an array in python, how to create, delete, access, find the length of an array, basic array operations, etc. However, you can also find the python array examples from here.

What is an Array?

An array is a unique variable that keeps more than one value at a time. For example, there is a list of car names. The storing of car names in a single variable might be like as follows:

car1 = "Ford"

car2 = "Volvo"

car3 = "BMW"

Let’s assume that you want to loop through the cars and discover a specific one? or else what if you had 300 cars, not just 3 cars?

To answer such questions there is one solution ie., Arrays.

An array can maintain several values under a single name, and you can easily access the elements by concerning an index number.

Mostly, data structures use arrays to implement their algorithms. The two most important terms that everyone should aware of to grasp the Arrays concept are as follows:

  • Element: Each item stored in an array is known as an element.

  • Index: Each location of an element in an array has a numerical index, that is utilized to identify the element.

What is Python Array?

A Python Array is a collection of a common type of data structure that holds elements with the same data type. Also, it can be iterated and posses a number of built-in functions to manage them.

Whenever you want to operate with many values of the same python data type then Python Array is very useful. By using the module named array, you can handle Array in Python programming. Also, you can treat lists as arrays in python. In case you want to create an array by array module, elements of the array need to be of the same numeric type.

Why use Arrays in Python?

You can view many uses of arrays in python like saves a lot of time by the combination of arrays, python array programs reduce the total size of the code, as python assists you get rid of problematic syntax, unlike other languages.

When to use Arrays in Python?

Users who want to perform many variables which are of the same type can use Python arrays. Also, it is utilized to store a large collection of data. As it uses less memory, so python arrays are much faster than lists. Thearray.arraytype is just a thin wrapper on C arrays which provides space-efficient storage of basic C-style data types.

Advantages of using an Array in Python

Some of the benefits of using an array are listed below for quick reference:

  • It can manage very huge datasets efficiently.

  • Compare to lists, arrays can do faster calculations and analysis

  • Computationally-memory efficient

  • Various Functionalities in python packages. By using those diverse python packages leads to trend modeling, statistics, and visualization easier.

Array Representation

The declaration of arrays can be in various ways and diverse languages. The following image will make you understand easily about Array Representation. So, let’s take a look at it:

Array Declaration:

Representation of an Array:

According to the above illustration, the below points are very important and need to be considered:

  • Index begins with 0

  • The array length determines the capacity to store the elements.

  • Each element can be accessed through its index.

Basics of an Array in Python

Users can create new datatypes named arrays with the help of the NumPy package in python programming. NumPy arrays are optimized for numerical analyses and hold only a single data type.

Firstly, you need to import NumPy and then utilize the array() function to build an array. Here, thearray() function takes a list as an input.

Example:

import numpymy_array = numpy.array([0, 1, 2, 3, 4])print(my_array)In the above code, the type of my_array is a numpy.ndarray.print(type(my_array))<class 'numpy.ndarray'>

Syntax to Create an Array in Python

By using the following syntax, you can declare an array in python during initializing. Here is the syntax for creating an array:

arrayName = array.array(type code for data type, [array,items])

Where

  • Identifier: Define a name like you usually, do for variables

  • Module: Python has a special module for creating an array in Python, called “array” – you must import it before using it

  • Method: the array module has a method for initializing the array. It takes two arguments, type code, and elements.

  • Type Code: name the data type using the type codes available (look at the below module for the detailed list of type codes).

  • Elements: specify the array elements within the square brackets, for instance [39, 87, 965].

Creating Python Arrays

For the creation of an array of numeric values, it is mandatory to import the array module. For instance:

import array as arra = arr.array('d', [1.1, 3.5, 4.5])print(a)

Output:

array('d', [1.1, 3.5, 4.5])

In the above instance, the type of array created is float type. The letter d is a type code. It defines the type of an array while creating.

The list of most common type codes are as follows:

Code

C Type

Python Type

Min bytes

b

signed char

int

1

B

unsigned char

int

1

u

Py_UNICODE

Unicode

2

h

signed short

int

2

H

unsigned short

int

2

i

signed int

int

2

I

unsigned int

int

2

l

signed long

int

4

L

unsigned long

int

4

f

float

float

4

d

double

float

8

Python program to demonstrate Creation of Array

# importing "array" for array creations

import array as arr

# creating an array with integer type

a = arr.array('i', [1, 2, 3])

# printing original array

print ("The new created array is : ", end =" ")

for i in range (0, 3):

print (a[i], end =" ")

print()

# creating an array with float type

b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array

print ("The new created array is : ", end =" ")

for i in range (0, 3):

print (b[i], end =" ")

Output:

The new created array is : 1 2 3

The new created array is : 2.5 3.2 3.3

Accessing Python Array Elements

By using the indices, you can easily access elements of an array. The following is the syntax of accessing array elements in python:

Syntax:

Array_name[index value]

Example:

import array as arr

a = arr.array('i', [2, 4, 6, 8])

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

print("Second element:", a[1])

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

Output:

First element: 2

Second element: 4

Last element: 8

Removing Python Array Elements

There is a possibility to delete one or more elements from an array with the help of Python’s del statement. Look at the following code:

import array as arr

number = arr.array('i', [1, 2, 3, 3, 4])

del number[2] # removing third element

print(number) # Output: array('i', [1, 2, 3, 4])

del number # deleting entire array

print(number) # Error: array is not defined

Output:

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

Traceback (most recent call last):

File "<string>", line 9, in <module>

print(number) # Error: array is not defined

NameError: name 'number' is not defined

Moreover, we can also make use of theremove()method to remove the given element, andpop()method to delete an element at the given index.

# Python program to demonstrate

# Removal of elements in a Array

# importing "array" for array operations

import array

# initializing array with array values

# initializes array with signed integers

arr = array.array('i', [1, 2, 3, 1, 5])

# printing original array

print ("The new created array is : ", end ="")

for i in range (0, 5):

print (arr[i], end =" ")

print ("\r")

# using pop() to remove element at 2nd position

print ("The popped element is : ", end ="")

print (arr.pop(2))

# printing array after popping

print ("The array after popping is : ", end ="")

for i in range (0, 4):

print (arr[i], end =" ")

print("\r")

# using remove() to remove 1st occurrence of 1

arr.remove(1)

# printing array after removing

print ("The array after removing is : ", end ="")

for i in range (0, 3):

print (arr[i], end =" ")

Output:

The new created array is : 1 2 3 1 5

The popped element is : 3

The array after popping is : 1 2 1 5

The array after removing is : 2 1 5

Finding the length of an array in Python

The length of an array defines as the number of elements existing in an array. It results in an integer value that equals the total number of elements present in that array.

Syntax: len(array_name)

Example:

cars = ["Ford", "Volvo", "BMW"]

x = len(cars)

​print(x)

Output:

3

Looping Array Elements in Python

By using the for in loop to loop via all the elements of an array, we can easily loop python array elements.

cars = ["Ford", "Volvo", "BMW"]

for x in cars:

print(x)

Output:

Ford

Volvo

BMW

Changing and Adding Elements

Python arrays are mutable, as their elements can be modified in the same way as lists.

import array as arr

numbers = arr.array('i', [1, 2, 3, 5, 7, 10])

# changing first element

numbers[0] = 0

print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])

# changing 3rd to 5th element

numbers[2:5] = arr.array('i', [4, 6, 8])

print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

Output:

array('i', [0, 2, 3, 5, 7, 10])

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

Here, we can add one item to the array with theappend() method, or add many items using the extend() method.

import array as arr

numbers = arr.array('i', [1, 2, 3])

numbers.append(4)

print(numbers) # Output: array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array

numbers.extend([5, 6, 7])

print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])

Result:

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

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

Array Concatenation in Python

In python programming, we can also concatenate two arrays by using the + operator.

import array as arr

odd = arr.array('i', [1, 3, 5])

even = arr.array('i', [2, 4, 6])

numbers = arr.array('i') # creating empty array of integer

numbers = odd + even

print(numbers)

Output:

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

Slicing Python Arrays

With the help of a slicing operator:, it is easy to access a range of items in an array.

import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]

numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th

print(numbers_array[:-5]) # beginning to 4th

print(numbers_array[5:]) # 6th to end

print(numbers_array[:]) # beginning to end

Output:

array('i', [62, 5, 42])

array('i', [2, 5, 62])

array('i', [52, 48, 5])

array('i', [2, 5, 62, 5, 42, 52, 48, 5])

Basic Array Operations

The following are some of the basic operations supported by an array:

  • Insertion – It adds an element at the given index.

  • Deletion – It deletes an element at the given index.

  • Update – It updates an element at the given index.

  • Search – It searches an element using the given index or by the value.

  • Traverse – It prints all the elements one by one.

Insertion Operation

It is used to insert one or more data elements into an array. You can insert a new element at the beginning, end, or any given index of the array by using this insertion operation in python. With the help of the python in-built insert() method, you can add a data element to the array.

Example:

from array import *


array1 = array('i', [10,20,30,40,50])


array1.insert(1,60)


for x in array1:

print(x)

Output:

10

60

20

30

40

50

Deletion Operation

The basic deletion python array operation helps users to remove an existing element from the array and re-organizing all elements of an array. By using the python in-built remove() method, here we are deleting a data element at the middle of the array.

from array import *

array1 = array('i', [10,20,30,40,50])

array1.remove(40)

for x in array1:

print(x)

Output:

10

20

30

50

Update Operation

This python array operation is referred to updating a current element from an array at a given index. Also, we can reassign a new value to the aspired index, if needed to update.

Code:

from array import *

array1 = array('i', [10,20,30,40,50])

array1[2] = 80

for x in array1:

print(x)

Output:

10

20

80

40

50

Search Operation

If you want to search an element of your requirement from an array then you can use the python in-built index() method. Because it can be performed based on its value or its index.

Code:

from array import *

array1 = array('i', [10,20,30,40,50])

print (array1.index(40))

Output:

3

Traverse Operation

There is a chance to traverse a Python array by taking the help of loops, that shown below.

Code:

import array

balance = array.array('i', [300,200,100])

for x in balance:

print(x)

Output:

300

200

100

How to Reverse an Array in Python?

The syntax used to reverse the entire array is as follows:

Syntax: array.reverse()

Example:

import array as myarray

number = myarray.array('b', [1,2, 3])

number.reverse()

print(number)

Result:

array('b', [3, 2, 1])

Array Methods in Python

A few basic array methods that you should memorize are append(), pop(), and more. They allow you to add and remove elements from an array. Want to gain more knowledge about the python array methods in-depth, then have a look at the below table that represents the main array methods in python:

Method

Description

append()

Adds an element at the end of the list

clear()

Removes all the elements from the list

copy()

Returns a copy of the list

count()

Returns the number of elements with the specified value

extend()

Add the elements of a list (or any iterable), to the end of the current list

index()

Returns the index of the first element with the specified value

insert()

Adds an element at the specified position

pop()

Removes the element at the specified position

remove()

Removes the first item with the specified value

reverse()

Reverses the order of the list

sort()

Sorts the list

Python Lists Vs Arrays

The lists can be treated as arrays in python programming. But, we cannot compel the type of elements saved in a list. For instance:

# elements of various types

a = [1, 3.5, "Hello"]

In case, you have created arrays with the array module then all array elements should be of the same numeric type.

import array as arr

# Error

a = arr.array('d', [1, 3.5, "Hello"])

Output:

Traceback (most recent call last):

File "<string>", line 3, in <module>

a = arr.array('d', [1, 3.5, "Hello"])

TypeError: must be real number, not str

Python Array Examples

Here are some of the array examples using Python programming that helps beginners and developers to gain quick knowledge on python array concepts.

Example of an Array operation

import numpy as np


array_A = np.array([1, 2, 3])

array_B = np.array([4, 5, 6])


print(array_A + array_B)

Output:

[5 7 9]

Example of Array indexing

import numpy as np


months_array = np.array(['Jan', 'Feb', 'March', 'Apr', 'May'])

print(months_array[3])

Result:

Apr

Interactive Example of a List to an Array

# IMPORT numpy as np

import numpy as np

# Lists

prices = [170.12, 93.29, 55.28, 145.30, 171.81, 59.50, 100.50]

earnings = [9.2, 5.31, 2.41, 5.91, 15.42, 2.51, 6.79]

# NumPy arrays

prices_array = np.array(prices)

earnings_array = np.array(earnings)

# Print the arrays

print(prices_array)

print(earnings_array)

Output:

[170.12 93.29 55.28 145.3 171.81 59.5 100.5 ]

[ 9.2 5.31 2.41 5.91 15.42 2.51 6.79]