Why Use Arrays?

Creating Arrays in Python

Python does not have built-in support for arrays, but it offers a list object which can be used similarly. However, for numeric arrays, Python provides a specialized array module which can be used to create arrays with elements of a specific type.

Python List as an Array

# Creating a list
my_list = [10, 20, 30, 40, 50]
print(my_list)

Using the array Module

from array import array

# Creating an array of integer type
my_array = array('i', [10, 20, 30, 40, 50])
print(my_array)

Accessing Array Elements

Array elements can be accessed using their index. Indices in arrays start from 0, meaning that the first element of the array is accessed by 0, the second element by 1, and so on.

# Accessing the first element
print(my_list[0])  # Output: 10
print(my_array[0])  # Output: 10

Modifying Array Elements

Array elements can be modified by accessing them using their index and then assigning a new value.

# Modifying the first element
my_list[0] = 100
my_array[0] = 100

print(my_list)  # Output: [100, 20, 30, 40, 50]
print(my_array)  # Output: array('i', [100, 20, 30, 40, 50])

Basic Operations