Python Arrays

Using the Array Module

To use arrays in Python, you need to import the array module and create an array.

Arrays can only hold elements of the same type, specified by a type code.

Tutorials dojo strip
import array as arr

# Creating an integer array
numbers = arr.array('i', [1, 2, 3, 4, 5])
print(numbers)  # Output: array('i', [1, 2, 3, 4, 5])

Accessing Array Elements

You can access individual elements in an array using indexing.

The index 0 accesses the first element, similar to lists.

print(numbers[0])  # Output: 1
print(numbers[2])  # Output: 3

Modifying Array Elements

Arrays are mutable, meaning you can change their elements after creation.

You can modify elements by accessing them using their index.

numbers[1] = 20
print(numbers)  # Output: array('i', [1, 20, 3, 4, 5])

Adding and Removing Elements

You can add elements to an array using the append() method and remove elements using the remove() method or the pop() method.

  • append() adds an element to the end of the array.
  • remove() removes the first occurrence of a specified value.
  • pop() removes an element at a specified index and returns it.
numbers.append(6)
print(numbers)  # Output: array('i', [1, 20, 3, 4, 5, 6])

numbers.remove(20)
print(numbers)  # Output: array('i', [1, 3, 4, 5, 6])

removed_element = numbers.pop(2)
print(removed_element)  # Output: 4
print(numbers)          # Output: array('i', [1, 3, 5, 6])

Python Arrays Example Code

This program creates arrays, accesses and modifies elements, adds and removes elements.

import array as arr

# Using the array module
# Creating an integer array
numbers = arr.array('i', [1, 2, 3, 4, 5])
print(numbers)  # Output: array('i', [1, 2, 3, 4, 5])

# Accessing elements
print(numbers[0])  # Output: 1

# Modifying elements
numbers[1] = 20
print(numbers)  # Output: array('i', [1, 20, 3, 4, 5])

# Adding and removing elements
numbers.append(6)
print(numbers)  # Output: array('i', [1, 20, 3, 4, 5, 6])

numbers.remove(20)
print(numbers)  # Output: array('i', [1, 3, 4, 5, 6])

removed_element = numbers.pop(2)
print(removed_element)  # Output: 4
print(numbers)          # Output: array('i', [1, 3, 5, 6])

Python Labs

Tutorials dojo strip
Tutorials dojo strip
Scroll to Top