Login Register

What are Arrays In Python?

What are Arrays?

  • An array is a powerful functionality that we use to store multiple items together in a single variable, where all items have the same type.
  • We also know about Python lists, but arrays are more memory-efficient and better for numerical computations.
  • You can use Python’s built-in array module for basic arrays or the NumPy library for advanced operations.

Let’s learn some key points about arrays:

  • All elements must be the same data type. For example, all integers or all floats.
  • Data is stored in contiguous memory, which makes accessing elements faster.
  • Arrays are best for large datasets or numerical calculations.

Simple Difference Between Array vs List in Python

FeatureArrayList
Element TypeIt contains same typeIt can contain mixed types
Memory UsageMore memory-efficientLess efficient
PerformanceFaster for numerical operations and large datasetsSlower for large operations
Implementation ProcessRequires array or NumPy moduleBuilt-in to Python

How To Create Arrays In Python?

Python provides a built-in array module to create arrays. Let’s understand the syntax:

Syntax for Creating Arrays

from array import array
array(typecode, [elements])
  • typecode: It defines the type of array elements (i for integers, f for floats, etc.).
  • elements: This refers to a list of initial values for the array.

Example 1: Integer Array

from array import array

# Create an integer array
numbers = array('i', [5, 10, 15, 20])

# Accessing elements
print("First element:", numbers[0])
print("All elements:", numbers)

Output of the code:

First element: 5
All elements: array('i', [5, 10, 15, 20])

Example 2: Float Array

from array import array

# Create a float array
temperatures = array('f', [36.5, 37.2, 36.8])

# Add a new value
temperatures.append(37.0)

print("Temperature readings:", temperatures)

Output of float array:

Temperature readings: array('f', [36.5, 37.2, 36.8, 37.0])

Exaplanation:

  • We use an array(‘i’, […]) for integers, and an array(‘f’, […]) for floats.

Essentials Operations on Python Arrays

We can access, modify, add, and remove elements using the following modules:

1. Accessing and Modifying Elements

You can access and modify elements of an array using their index. Example code:

from array import array

# Create an integer array
numbers = array('i', [5, 10, 15, 20, 25])

# Access elements by index
print("First element:", numbers[0])
print("Last element:", numbers[-1])

# Modify an element
numbers[2] = 30
print("Modified array:", numbers)

Code Output:

First element: 5
Last element: 25
Modified array: array('i', [5, 10, 30, 20, 25])
  • We used numbers[index] to access or change a value.
  • Always remember that negative indexing allows access from the end.

2. Adding, Removing, and Traversing Elements

from array import array

# Create a float array
temps = array('f', [36.5, 37.0, 36.8])

# Add elements
temps.append(37.2) # Add single element
temps.extend([36.9, 37.1]) # Add multiple elements

# Remove elements
temps.remove(37.0) # Remove specific value
temps.pop() # Remove last element

# Traverse and print
for t in temps:
print(t, end=" ")

Output:

36.5 36.8 37.2 36.9 

Explanations of the code:

  • append() → Adds a single value at the end.
  • extend() → Adds multiple values.
  • remove() → Deletes a specific value.
  • pop() → Deletes the last element.
  • for loop to traverse and print elements

Advanced Array Operations with NumPy

NumPy is a powerful library in Python that is useful for handling arrays. This library supports multi-dimensional data and fast mathematical operations.

Let’s learn about its operations:

Example 1: Creating and Manipulating 1D Arrays

import numpy as np

# Create a 1D array of exam scores
scores = np.array([80, 90, 75, 85, 95])

# Increase all scores by 5 points
adjusted_scores = scores + 5

# Print results
print("Original Scores:", scores)
print("Adjusted Scores:", adjusted_scores)

Expected Output:

Original Scores: [80 90 75 85 95]
Adjusted Scores: [85 95 80 90 100]
  • NumPy allows element-wise arithmetic on arrays.
  • Here, +5 is applied to all elements at once instead of using loops.

Example 2: Working with 2D Arrays (Matrices)

import numpy as np

# Create a 2x3 matrix representing daily sales of 2 stores
sales = np.array([[10, 12, 15],
[8, 9, 14]])

# Calculate total sales per store (row-wise sum)
total_sales = np.sum(sales, axis=1)

# Print results
print("Sales Matrix:\n", sales)
print("Total Sales per Store:", total_sales)

Output:

Sales Matrix:
[[10 12 15]
[ 8 9 14]]
Total Sales per Store: [37 31]

In this code:

  • 2D arrays can store structured data like matrices.
  • np.sum(…, axis=1) calculates the sum of each row (total sales per store).

Real-Life Use Cases of Python Arrays

  1. Data Analysis: Arrays help to store and process huge datasets quickly, like sales records, student scores, or sensor readings.
  2. Scientific Computing: Arrays are used for fast calculations on numbers in physics, chemistry, and engineering fields.
  3. Graphics and Gaming: Arrays can store coordinates, colors, and pixel information for images, animations, or game objects.

Limitations of Arrays

  1. Type Restriction: All elements in an array must be of the same type (all numbers, all floats, etc.), but lists are allowed mixed types.
  2. Less Versatile than Lists: Arrays are not as flexible as lists for general tasks like adding different types of data, storing text with numbers, and more.

Exercise: Track Daily Steps Using an Array

Track your daily step count for a week and find:

  1. Your total steps in the week.
  2. The day with the maximum steps.
  3. The average steps per day.

Instructions:

  • Use a Python array to store the steps for 7 days.
  • Use loops and array operations to calculate the results.

Expected Output:

Total steps this week: 47900
Maximum steps were on day 5: 10000
Average steps per day: 6843

Write this code manually by yourself. If you have any questions about this topic, you can freely ask in our Q&A section.