Python Array

Rumman Ansari   Software Engineer   2023-06-01   142 Share
☰ Table of Contents

Table of Content:


Python Array

In Python, an array is a type of data structure that can hold a fixed number of elements of the same data type. The array module in Python provides an implementation of arrays that are more memory-efficient compared to lists.

The array module allows you to create arrays of different data types, such as integers, floating-point numbers, and characters. It provides a way to store a large amount of data in a contiguous block of memory.

Here's an example of using the array module to create and work with an array:


import array

# Create an array of integers
my_array = array.array('i', [1, 2, 3, 4, 5])

# Access elements of the array
print(my_array[0])  # Output: 1
print(my_array[3])  # Output: 4

# Modify elements of the array
my_array[2] = 10
print(my_array)  # Output: array('i', [1, 2, 10, 4, 5])

# Get the length of the array
array_length = len(my_array)
print("Length of array:", array_length)  # Output: 5

# Append an element to the array
my_array.append(6)
print(my_array)  # Output: array('i', [1, 2, 10, 4, 5, 6])

# Remove an element from the array
del my_array[2]
print(my_array)  # Output: array('i', [1, 2, 4, 5, 6])

In this example, we import the array module and create an array of integers using the 'i' typecode. We can access and modify elements of the array, get its length, append elements, and remove elements using the methods provided by the array module.

It's important to note that the array module requires all elements in the array to be of the same type. Unlike lists, arrays created using the array module have a fixed size and cannot be resized dynamically.