Arrays in Python

Our first program will demonstrate how to work with arrays in Python. Here’s the full source code with explanations:

import numpy as np

# In Python, we can create arrays using lists or the NumPy library
# for more efficient array operations

# Create a list (Python's built-in array-like structure)
a = [0] * 5
print("emp:", a)

# Set a value at an index
a[4] = 100
print("set:", a)
print("get:", a[4])

# Get the length of the list
print("len:", len(a))

# Create and initialize a list in one line
b = [1, 2, 3, 4, 5]
print("dcl:", b)

# In Python, we don't need to specify the size upfront
b = [1, 2, 3, 4, 5]
print("dcl:", b)

# To create an array with specific indices, we can use a dictionary
c = {0: 100, 3: 400, 4: 500}
print("idx:", [c.get(i, 0) for i in range(5)])

# For multi-dimensional arrays, we can use nested lists
# or NumPy arrays for better performance
two_d = [[0 for _ in range(3)] for _ in range(2)]
for i in range(2):
    for j in range(3):
        two_d[i][j] = i + j
print("2d: ", two_d)

# Create and initialize a 2D array at once
two_d = [
    [1, 2, 3],
    [1, 2, 3]
]
print("2d: ", two_d)

# Using NumPy for more efficient array operations
np_array = np.array([1, 2, 3, 4, 5])
print("NumPy array:", np_array)

# Create a 2D NumPy array
np_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D NumPy array:", np_2d)

To run the program, save the code in a file (e.g., arrays.py) and use the Python interpreter:

$ python arrays.py
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d:  [[0, 1, 2], [1, 2, 3]]
2d:  [[1, 2, 3], [1, 2, 3]]
NumPy array: [1 2 3 4 5]
2D NumPy array: [[1 2 3]
 [4 5 6]]

Note that Python lists are more flexible than arrays in some languages. They can hold elements of different types and can be resized dynamically. For more efficient numerical computations, especially with large datasets, the NumPy library provides a powerful array object that offers better performance and additional functionality.

When working with arrays in Python, keep in mind:

  1. Python lists are the built-in array-like structure and are very flexible.
  2. You can access and modify elements using square bracket notation [].
  3. The len() function returns the length of a list.
  4. Multi-dimensional arrays can be created using nested lists.
  5. For more advanced array operations, especially in scientific computing, the NumPy library is commonly used.

This example demonstrates basic array operations in Python, including creation, modification, and accessing elements in both one-dimensional and two-dimensional structures.