In this Tutorial of Python Arrays, You’ll learn the following topics in a detailed way:
- What is an Array?
- What is Python Array?
- Why use Arrays in Python?
- When to use Arrays in Python?
- Advantages of using an Array
- Array Representation
- Basics of an Array in Python
- Syntax to Create an Array in Python
- Creating Python Arrays
- Accessing Python Array Elements
- Removing Python Array Elements
- Finding the length of an array in Python
- Looping Array Elements in Python
- Changing and Adding Elements
- Array Concatenation in Python
- Slicing Python Arrays
- Basic Array Operations
- How to Reverse an Array in Python?
- Python Array Methods
- Python Lists Vs Arrays
- Python Array Examples
- Python Programming Tutorial
- Python Programming Examples
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.
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.
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.
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. The
array.arraytype is just a thin wrapper on C arrays which provides space-efficient storage of basic C-style data types.
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.
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:
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.
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, the
array() function takes a list as an input.
import numpy my_array = numpy.array([0, 1, 2, 3, 4]) print(my_array)
In the above code, the type of
my_array is a
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])
- 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].
For the creation of an array of numeric values, it is mandatory to import the array module. For instance:
import array as arr a = arr.array('d', [1.1, 3.5, 4.5]) print(a)
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|
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 =" ")
The new created array is : 1 2 3 The new created array is : 2.5 3.2 3.3
By using the indices, you can easily access elements of an array. The following is the syntax of accessing array elements in python:
import array as arr a = arr.array('i', [2, 4, 6, 8]) print("First element:", a) print("Second element:", a) print("Last element:", a[-1])
First element: 2 Second element: 4 Last element: 8
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 # removing third element print(number) # Output: array('i', [1, 2, 3, 4]) del number # deleting entire array print(number) # Error: array is not defined
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 the
remove()method to remove the given element, and
pop()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 =" ")
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
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.
cars = ["Ford", "Volvo", "BMW"] x = len(cars) print(x)
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)
Ford Volvo BMW
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 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])
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 the
append() method, or add many items using the
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])
array('i', [1, 2, 3, 4]) array('i', [1, 2, 3, 4, 5, 6, 7])
In python programming, we can also concatenate two arrays by using the
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)
array('i', [1, 3, 5, 2, 4, 6])
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
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])
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.
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.
from array import * array1 = array('i', [10,20,30,40,50]) array1.insert(1,60) for x in array1: print(x)
10 60 20 30 40 50
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)
10 20 30 50
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.
from array import * array1 = array('i', [10,20,30,40,50]) array1 = 80 for x in array1: print(x)
10 20 80 40 50
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.
from array import * array1 = array('i', [10,20,30,40,50]) print (array1.index(40))
There is a chance to traverse a Python array by taking the help of loops, that shown below.
import array balance = array.array('i', [300,200,100]) for x in balance: print(x)
300 200 100
The syntax used to reverse the entire array is as follows:
import array as myarray number = myarray.array('b', [1,2, 3]) number.reverse() print(number)
array('b', [3, 2, 1])
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:
|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|
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"])
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
Here are some of the array examples using Python programming that helps beginners and developers to gain quick knowledge on python array concepts.
import numpy as np array_A = np.array([1, 2, 3]) array_B = np.array([4, 5, 6]) print(array_A + array_B)
[5 7 9]
import numpy as np months_array = np.array(['Jan', 'Feb', 'March', 'Apr', 'May']) print(months_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)
[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]