Skip to content

Python Array Vijetha Spark By {Examples}

  • by

We will discuss the basics of arrays in Python. The array is a collection of items of the same type and stored at the same size of a block in the memory. Python provides an array module for defining arrays. You can use array methods to perform various operations of arrays.

In this article, I will explain the basic concept and usage of arrays in Python. Also will explain using the array module how we can handle the arrays and using its methods how we can perform various actions of arrays.

Table of content :

What is an array

Difference between lists and arrays

How to create an array?

Find the length of an array

Access single python array element

Access multiple array elements using slicing

Iterate over the Python array

Array methods

Add elements to Python array

Append elements to an array

Remove elements from an array

1. What is Python Array

Python array is an object that allows a collection of items of the same data type and stores at the same size of a block in the memory. Items in the collection can be accessed using a zero-based index. It can be stored multiple values at a time. The length of the array is height index of an array plus one. For example, if an array contains 5 elements, the last index of the array is 4, the length of the array would be 4+1 which is 5.

Python doesn’t have a built-in array data type, you can represent lists as arrays. However, you can’t control the type of elements stored in a list. Whereas, in arrays you can store the same type of elements. And the data type it accepts are int and float.

2. Difference Between Lists and Arrays

In Python, lists are one of the most common data structure that are mutable and doesn’t have fixed size. It can be used to store elements of different data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type.

Whereas Python arrays allow elements of same data type. Due to the usage of less memory Python arrays are faster than the lists.

3. How to Create an Array?

You can create an array using the array() method of the array module of Python. It allows two arguments, type code, and value_list. You can use this module to create an array of specified datatypes and value lists specified in its arguments. Before going to create an array using array module you need to import array module. Alternatively, you can create arrays by using, NumPy module and Python lists.

If you want to use mathematical calculations the best option would be using the NumPy module to create an array. NumPy module arrays and list allows to store any data type of elements.

3. 1 Syntax of array()

# Syntax of array module
array(type code, value_list)

Type code: It specifies the type of elements which we want to store in an array.

Value_list: It specifies number of elements which we want to store in an array. Each element is seperated by a comma. If you don’t pass this argument you can create an empty array.

Below is the type code table, it contains different type codes using these codes you can create an Python array of specified data type.

Type codePython typeC TypeMin size(bytes)‘u’Unicode characterPy_UNICODE2‘b’IntSigned char1‘B’IntUnsigned char1‘h’IntSigned short2‘l’IntSigned long4‘L’IntUnsigned long4‘q’IntSigned long long8‘Q’IntUnsigned long long8‘H’IntUnsigned short2‘f’FloatFloat4‘d’FloatDouble8‘i’IntSigned int2‘I’IntUnsigned int2Type code Table

Example 1:

You can use type code parameter to pass character for specifing datatype of given elements.

# Create an Array
# Import “array” for array creations
import array as arr

# Create an array of integer type
arr1 = arr.array(‘i’, [2, 4, 6, 8])

print(“Array is : “, end=” “)
for i in range(0, 4):
print(arr1[i], end=” “)

Yields below output.

Example 2:

Let’s create array of floating values.

# Create an array of float type
arr1 = arr.array(‘d’, [2.0, 4.0, 6.0, 8.0])
print(“Array is : “, end=” “)
for i in range(0, 4):
print(arr1[i], end=” “)

Yields below output.

4. Get the Length of an Array

Python len() is a built-in function, which is used to get the total number of elements present in the given array. Length of the array is equal to the total number of elements in the list.

Syntax of len() Function:

# Syntax of len() function
len(array)

Let’s pass an array as an argument to get the number of elements inside the array.

# Get the length of an array using len()
arr = [1,3,6,9,12,15,20,22,25]
print(“Array is:”, arr)
print(“Length of an array:”, len(arr))

# Output:
# Array is : [1,3,6,9,12,15,20,22,25]
# Length of an array: 9

5. Access Array Element

You can access a single element in an array by using its index. Use the index operator [] to access specified element in an array. The index must be an integer. 

# Import array module
import array as arr

# Create an array of integer type
arr1 = arr.array(‘i’, [2, 4, 6, 8])
print(“Array is : “, end=” “)

# Access array elements using index
print(“First element:”, arr1[0])
print(“Second element:”, arr1[1])
print(“Last element:”, arr1[-1])

# Output:
# First element: 2
# Second element: 4
# Last element: 8

6. Access Multiple Array Elements using Slicing

Moreover, you can use the slicing operator to access specified range of elements present in the array. Let’s apply the slicing operator over the given array and get the specified selection of an array.

# Access array elements using slicing
import array as arr

# Create an array using array module
arr1 = arr.array(‘i’, [2, 4, 6, 8])
print(“Given array is : “, arr1)
print(“Specified portion of an array:”, arr1[:3])

# Output:
# Given array is : array(‘i’, [2, 4, 6, 8])
# Specified portion of array: array(‘i’, [2, 4, 6])

7. Iterate Over the Python Array

You can iterate arrays using for loop to access each element presents in the array. Use For loop in Python over the sequence or iterable objects such as lists, sets, strings, tuples, and dictionary to perform various operations in Python.

# Create an array of integers
arr1 = arr.array(‘i’, [0, 2, 4, 6, 2])
print(“Given array:”, arr1)

# Iterate an array using for loop
for i in range(len(arr1)):
print(arr1[i])

# Output:
# Given array: array(‘i’, [0, 2, 4, 6, 2])
# 0
# 2
# 4
# 6
# 2

8. Array Methods

Python doesn’t have a built-in data type of an array, hence, you can use a set of list built-in functions over the arrays to perform various actions like adding, updating, deleting, sorting, and searching of array elements.

MethodArray/List Method Descriptionappend()Adds an element at the end of the listclear()Removes all the elements from the listcopy()Returns a copy of the listcount()Returns the number of elements with the specified valueextend()Add the elements of a list (or any iterable), to the end of the current listindex()Returns the index of the first element with the specified valueinsert()Adds an element at the specified positionpop()Removes the element at the specified positionremove()Removes the first item with the specified valuereverse()Reverses the order of the listsort()Sorts the list

9. Add Elements to Python Array

You can add elements by using its index. Using index [] operator you can add/change the elements of an array. For example

import array as arr

# Create an array using array module
# Add elements to an array
arr1 = arr.array(‘i’, [2, 4, 6, 8])
print(“Given array is : “, arr1)
arr1[1] = 3
arr1[3] = 5
print(“New array:”, arr1)

# Output:
# Given array is : array(‘i’, [2, 4, 6, 8])
# New array: array(‘i’, [2, 3, 6, 5])

You can also use the insert() method to add an element at a specific index of the array. For example, you use the insert() method to add the integer 2 at the index 1 of the array. The existing elements are shifted to the right to make room for the new element.

# Create an array of integers
arr1 = arr.array(‘i’, [0, 4, 6, 8])

# Add elements to array using insert()
arr1.insert(1, 2)
print(numbers)

# Output
# array(‘i’, [0, 2, 4, 6, 8])

You can also use extend() method to add elements to an array by appending all the elements of another iterable (such as a list, tuple, or another array) to the end of the array.

# Create an array of integers
arr1 = arr.array(‘i’, [5, 10, 15])

# Create a list of integers
mylist = [20, 25, 30]

# Use extend() method to array module
arr1.extend(mylist)
print(arr)

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

10. Append Elements to Python Array

You can use the array module to provide a array() function that creates an array object, which is similar to a list but more efficient for certain types of data. The array object has its own append() method that you can use to append elements to the end of the array.

For example, you first import the array module and then use the array() function to create an integer array arr with four elements. You use the append() method of the arr object to add an integer 8 to the end of the array.

import array as arr
# Create an array of integers
arr1 = arr.array(‘i’, [0, 2, 4, 6])

# Append the elements to an array
arr1.append(8)
print(arr1)

# Output
# array(‘i’, [0, 2, 4, 6, 8])

11. Remove Elements from Python Array

In Python use built-in remove() function to remove elements from an array. To pass specified element(which we want to remove) into remove(), it will remove those element from the array. If the passed element doesn’t exist in the array, it can raise the ValueError.

# Create an array of integers
arr1 = arr.array(‘i’, [0, 2, 4, 6])
print(“Given array:”, arr1)
# Remove an element from an array
arr1.remove(4)
print(“After removing array is:”, arr1)

# Output:
# Given array: array(‘i’, [0, 2, 4, 6])
# After removing array is: array(‘i’, [0, 2, 6])

If array has a number with multiple occurrence, remove() method will remove only first occurrence of those number.

# Create an array of integers
arr1 = arr.array(‘i’, [0, 2, 4, 6, 2])
print(“Given array:”, arr1)
# Remove an element from an array
arr1.remove(2)
print(“After removing array is:”, arr1)

# Output:
# Given array: array(‘i’, [0, 2, 4, 6, 2])
# After removing array is: array(‘i’, [0, 4, 6, 2])

pop() function can also be used to remove and return an element from the array. By default it removes only the last element of the array. If we remove specified element you can pass its corresponding index into pop() function.

import array as arr
# Create an array of integers
arr1 = arr.array(‘i’, [0, 2, 4, 6, 2])
print(“Given array:”, arr1)
# Remove an element from an array
arr1.pop(2)
print(“After removing array is:”, arr1)

# Output:
# Given array: array(‘i’, [0, 2, 4, 6, 2])
# After removing array is: array(‘i’, [0, 2, 6, 2])

12. Conclusion

In this article, I have explained the basic concept and usage of arrays in Python. Also explained using the array module how we can define the arrays and using its methods how we can perform various actions of arrays.

Note that arrays are used to store elements of the same datatype and the it accepts int and float data types.

 We will discuss the basics of arrays in Python. The array is a collection of items of the same type and stored at the same size of a block in the memory. Python provides an array module for defining arrays. You can use array methods to perform various operations of arrays. In this article, I  Read More Python, Python Tutorial, Python array 

Leave a Reply

Your email address will not be published. Required fields are marked *