Loading...

Go Back

Next page
Go Back Course Outline

Python Full Course


Arrays in Python

Arrays in Python

While Python doesn't have a built-in data type for arrays in the same way as some other programming languages (like C++), it provides the array module which allows you to create arrays of a specific numeric type. Additionally, Python's lists are often used for similar purposes and offer more flexibility.

Using the array Module

The array module in Python is used to create arrays with elements of a consistent numeric type. This can be more memory-efficient when you need to store a large number of numerical values of the same type.

Creating Arrays

To create an array using the array module, you first need to import it and then use the array.array(typecode, initializer) constructor.

  • typecode: A character representing the type of the elements in the array (e.g., 'i' for signed integer, 'f' for float).
  • initializer: An optional iterable (like a list or tuple) containing the initial values for the array.
import array
                        
# Create an array of integers integer_array = array.array('i', [1, 2, 3, 4, 5]) print(f"Integer Array: {integer_array}") # Create an array of floats float_array = array.array('f', [1.0, 2.5, 3.7, 4.2]) print(f"Float Array: {float_array}")
Integer Array: array('i', [1, 2, 3, 4, 5])
Float Array: array('f', [1.0, 2.5, 3.7, 4.2])

Common Typecodes

Here are some common typecodes used with the array module:

  • 'b': Signed byte
  • 'B': Unsigned byte
  • 'h': Signed short integer
  • 'H': Unsigned short integer
  • 'i': Signed integer
  • 'I': Unsigned integer
  • 'l': Signed long integer
  • 'L': Unsigned long integer
  • 'f': Float
  • 'd': Double-precision float

Accessing Array Elements

You can access elements of an array using their index (0-based), just like with lists.

import array
                        
                        my_array = array.array('i', [10, 20, 30, 40])
                        print(f"Element at index 0: {my_array[0]}")
                        print(f"Element at index 2: {my_array[2]}")
                        
Element at index 0: 10
Element at index 2: 30

Array Operations

The array module supports various operations, such as appending elements, inserting elements, removing elements, and more.

import array
                        
                        my_array = array.array('i', [1, 2, 3])
                        print(f"Initial array: {my_array}")
                        
                        # Append an element
                        my_array.append(4)
                        print(f"After appending 4: {my_array}")
                        
                        # Insert an element at a specific index
                        my_array.insert(1, 15)
                        print(f"After inserting 15 at index 1: {my_array}")
                        
                        # Remove the first occurrence of an element
                        my_array.remove(2)
                        print(f"After removing 2: {my_array}")
                        
                        # Pop the last element
                        popped_element = my_array.pop()
                        print(f"Popped element: {popped_element}, Array after pop: {my_array}")
                        
Initial array: array('i', [1, 2, 3])
After appending 4: array('i', [1, 2, 3, 4])
After inserting 15 at index 1: array('i', [1, 15, 2, 3, 4])
After removing 2: array('i', [1, 15, 3, 4])
Popped element: 4, Array after pop: array('i', [1, 15, 3])

Using Python Lists as Arrays

Python lists are more commonly used as dynamic arrays. They can hold elements of different data types and are very flexible.

Creating Lists

# Creating lists
                        my_list = [1, 2, 3, 4, 5]
                        mixed_list = [1, "hello", 3.14, True]
                        empty_list = []
                        
                        print(f"Integer List: {my_list}")
                        print(f"Mixed List: {mixed_list}")
                        print(f"Empty List: {empty_list}")
                        
Integer List: [1, 2, 3, 4, 5]
Mixed List: [1, 'hello', 3.14, True]
Empty List: []

Accessing List Elements

List elements are also accessed using their index.

my_list = [100, 200, 300]
                        print(f"First element of list: {my_list[0]}")
                        print(f"Last element of list: {my_list[-1]}") # Negative indexing
                        
First element of list: 100
Last element of list: 300

List Operations

Lists support a wide range of operations, including appending, extending, inserting, removing, slicing, and more.

my_list = [1, 2, 3]
                        print(f"Initial list: {my_list}")
                        
                        # Append an element
                        my_list.append(4)
                        print(f"After appending 4: {my_list}")
                        
                        # Extend with another list
                        my_list.extend([5, 6])
                        print(f"After extending with [5, 6]: {my_list}")
                        
                        # Insert at a specific index
                        my_list.insert(0, 0)
                        print(f"After inserting 0 at index 0: {my_list}")
                        
                        # Remove a specific element
                        my_list.remove(3)
                        print(f"After removing 3: {my_list}")
                        
                        # Pop an element by index (default is the last)
                        popped_element = my_list.pop(1)
                        print(f"Popped element at index 1: {popped_element}, List after pop: {my_list}")
                        
Initial list: [1, 2, 3]
After appending 4: [1, 2, 3, 4]
After extending with [5, 6]: [1, 2, 3, 4, 5, 6]
After inserting 0 at index 0: [0, 1, 2, 3, 4, 5, 6]
After removing 3: [0, 1, 2, 4, 5, 6]
Popped element at index 1: 1, List after pop: [0, 2, 4, 5, 6]

NumPy Arrays

For more advanced numerical operations and multi-dimensional arrays, the NumPy library is widely used in Python. NumPy arrays are more efficient for numerical computations than standard Python lists, especially for large datasets.

To use NumPy arrays, you need to install the NumPy library first (pip install numpy) and then import it.

import numpy as np
                        
                        # Creating a NumPy array
                        numpy_array = np.array([1, 2, 3, 4, 5])
                        print(f"NumPy Array: {numpy_array}")
                        
                        # Multi-dimensional array
                        multi_dim_array = np.array([[1, 2], [3, 4]])
                        print(f"Multi-dimensional NumPy Array:\n{multi_dim_array}")
                        
NumPy Array: [1 2 3 4 5]
Multi-dimensional NumPy Array:
[[1 2]
[3 4]]

In summary, while Python's built-in lists are versatile and often used as arrays, the array module provides a more type-constrained array for numerical data, and NumPy offers powerful array objects for advanced numerical computing.

Go Back

Next page