Python is a high-level, interpreted programming language. It is widely used for web development, scientific computing, data analysis, artificial intelligence, and more. It is known for its simplicity and ease of use, making it a popular choice for beginners and experienced developers alike.
The article explains the details of array in Python. Let's get started.
Array in Python
An Array in Python is a collection of items stored in a contiguous memory block. The items in an array can be of any data type, and integers index them. Arrays are commonly used to store collections of data, such as lists of numbers, strings, or other objects.
In Python, Arrays can be created using the built-in "array" module. The "array" class has a variety of methods and attributes that can be used to manipulate the data stored in the array. For example, the "append" method can be used to add new items to the end of the array, and the "pop" method can be used to remove an item from the end of the Array.
Representation of Array
In Python, arrays can be represented using the built-in "array" module. To create an array, you first need to import the "array" module and then call the "array" function with the type code of the items you want to store in the Array, followed by an iterable containing the items. For example, to create an array of integers, you can use the following code:
from array import array
You can also try this code with Online Python Compiler
In this example, "i" is the type code for integers, and the array is initialized with the values [1, 2, 3, 4, 5].
The type codes that can be used with the "array" function include:
Type code
Python code
"b"
for signed byte
"B"
for unsigned byte
"u"
for Unicode char
"h"
for short
"H"
for unsigned short
"i"
for int
"I"
for unsigned int
"l"
for long
"L"
for unsigned long
"f"
for float
"d"
for double
Alternatively, the array can be represented using the numpy library, which provides more advanced array manipulation capabilities. Here is an example of creating an array of integers using numpy:
import numpy as np
You can also try this code with Online Python Compiler
In this example, the "np.array" function is used to create a numpy array and it's initialized with the values [1, 2, 3, 4, 5].
Array operations
There are several operations that can be performed on arrays in Python. Some of the most common array operations include:
Creating a array
Python's array module can be imported to generate an array. An array can be created by using the syntax array(data type, value list), which takes two arguments: a data type and a value list.
Example
import array
# Integer array
x = array.array('i', [1, 2, 3, 4, 5])
print ("Integer array: ", end =" ")
for i in range (0, 5):
print (x[i], end =" ")
print()
# creating an array
y = array.array('u', ['n', 'i', 'n', 'j', 'a', 's'])
print ("Character array: ", end =" ")
for i in range (0, 6):
print (y[i], end =" ")
You can also try this code with Online Python Compiler
You can practice by yourself with the help of online python compiler for better understanding.
Adding Elements to a Array
The Array can have elements added to it by using the built-in insert() function. The insert command can add one or more data elements to an array. At the start, end, or any specified index of the Array, a new element may be inserted depending on the necessity. The value specified in its arguments can also be added to the end of the Array using the append() function.
Example
import array
# Integer array
x = array.array('i', [4, 5, 6])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
print (x[i], end =" ")
print()
# inserting array using insert operation
x.insert(1, 7)
print ("Array after insertion : ", end =" ")
for i in (x):
print (i, end =" ")
print()
# Character array
y = array.array('u', ['n', 'i', 'n', 'j'])
print ("Array before insertion : ", end =" ")
for i in range (0, 4):
print (y[i], end =" ")
print()
#Using append() operation add element
y.append('s')
print ("Array after insertion : ", end =" ")
for i in (y):
print (i, end =" ")
print()
You can also try this code with Online Python Compiler
Use the index number to get at the array's items. To access a component in an array, type the index operator []. Integers are required for the index.
Example
import array
# Integer array
a = array.array('i', [0, 1, 2, 3, 4])
print("The access element is: ", a[1])
print("The access element is: ", a[3])
# Character element
b = array.array('u', ['n', 'i', 'n', 'j', 'a', 's'])
print("The access element is: ", b[3])
print("The access element is: ", b[5])
You can also try this code with Online Python Compiler
Using the Array's built-in remove() function, elements can be removed; however, if the element doesn't already exist in the set, an error is raised. Iterators are used to delete a range of elements because the Remove() method only removes one element at a time. However, by default, the pop() function only removes the last member of the Array. The element's index is supplied as an argument to the pop() method to remove an element from a specific place in the Array.
Example
import array
my_arr = array.array('i', [1, 3, 5, 1, 7])
# Print the original array
print ("The new created array is : ", end ="")
for i in range (0, 5):
print (my_arr[i], end =" ")
print ("\r")
# using pop() Operation remove element at 3rd position
print ("The popped element is : ", end ="")
print (my_arr.pop(4))
# Print the element after popping
print ("The array after popping is : ", end ="")
for i in range (0, 4):
print (my_arr[i], end =" ")
print("\r")
my_arr.remove(1)
# Print the element after removing
print ("The array after removing is : ", end ="")
for i in range (0, 3):
print (my_arr[i], end =" ")
You can also try this code with Online Python Compiler
There are other ways to print an array's entire contents, but we use the Slice operation to print a selected subset of the Array's elements. The Array is subjected to a slice operation using a colon (:). Use [:Index] to print elements from beginning to range, [:-Index] to print elements from range to end, [Index:] to print elements from particular Index to end, [Start Index:End Index] to print elements within range, and [:] to print entire List using slicing operation. Additionally, use [::-1] to print the entire Array in reverse order.
Example
import array
li = ['c', 'o', 'd', 'i', 'g', 'n', 'i', 'n', 'j', 's']
x = array.array('u', li)
print("Begining Array: ")
for i in (x):
print(i, end =" ")
# Print elements of a any range
# using Slice operation
Sliced_array = x[4:8]
print("\nSliced elements in a range 4-8: ")
print(Sliced_array)
# Print elements from a
# pre-defined point to end
Sliced_array = x[6:]
print("\nElements sliced from 6th "
"element till the end: ")
print(Sliced_array)
# Print elements from
#starting to till end
Sliced_array = x[:]
print("\nPrint all elements: ")
print(Sliced_array)
You can also try this code with Online Python Compiler
We use the index() method that is built into Python to search for a specific element in the array. The index of the first time a value mentioned in parameters appears is returned by this method.
Example
import array
#Integer array
my_arr = array.array('i', [1, 2, 1, 5, 3, 5])
# print the original array
print ("The new created array is : ", end ="")
for i in range (0, 6):
print (my_arr[i], end =" ")
print ("\r")
print ("The index of 1st occurrence of 5 is : ", end ="")
print (my_arr.index(5))
print ("The index of 1st occurrence of 1 is : ", end ="")
print (my_arr.index(1))
You can also try this code with Online Python Compiler
We just assign a new value to the target index we wish to change to update an element in the array.
Example
import array
my_arr = array.array('i', [1, 2, 5, 5, 2, 5])
# print the original array
print ("Array before update : ", end ="")
for i in range (0, 6):
print (my_arr[i], end =" ")
print ("\r")
my_arr[2] = 6
print("Array after update : ", end ="")
for i in range (0, 6):
print (my_arr[i], end =" ")
print()
# update the element in a array
my_arr[4] = 8
print("Array after updation : ", end ="")
for i in range (0, 6):
print (my_arr[i], end =" ")
You can also try this code with Online Python Compiler
You can use the built-in "len" function to check the length of an array. For example, to check the length of the array "my_array", you can use the following code:
len(my_array).
How can I create an empty array in Python?
You can create an empty array in Python using the "array" function with no initial values. For example, to create an empty array of integers, you can use the following code:
from array import array
my_array = array("i")
How can I sort an array in Python?
You can use the built-in "sorted" function to sort an array. For example, to sort the array "my_array", you can use the following code:
sorted_array = sorted(my_array)
Conclusion
In this article, we have extensively discussed the details of Array in Python, in which we talk about searching, slicing, updating, and removing elements.
We hope the blog has helped you enhance your knowledge regarding Array in Python.