Arrays in Python: Indexing, Matrices, and Windows

Learn Python 3 list indexing, 2D matrix traversal, and a sliding-window pattern with runnable exercises for learners who know loops and functions.

published: reading time: 5 min read author: Geek Workbench updated: November 5, 2026
Quick Summary

A practical Python 3 guide for readers who know loops and functions. Learn list indexing, row-by-row matrix traversal, and a two-pointer sliding window through runnable examples with expected output.

Arrays in Python: Indexing, Matrices, and Windows

If you know loops and functions but are still getting comfortable with arrays, this is a place to practice. All examples use Python 3’s built-in lists. We’ll start with one index, add a second coordinate for matrices, and finish by keeping two boundaries around a moving range.

Python calls its resizable sequence a list. A list behaves like a dynamic array for the operations in this guide, though it stores references to Python objects rather than a single block of packed numeric values.

1. Start with one-dimensional indexing

List indices start at zero. For a list with four elements, the valid positive indices are 0 through 3. Negative indices count from the end, so items[-1] means the last item.

scores = [12, 18, 15, 20]

print(scores[0])    # 12
print(scores[-1])   # 20
print(scores[1:3])  # [18, 15]

A slice includes its starting index and stops before its ending index. That stop-before rule is easy to miss: scores[1:3] returns positions 1 and 2.

Indexing and replacing an existing item take O(1) time. Finding a value in an unsorted list takes O(n), because Python may need to check every item. Appending is amortized O(1): most appends are quick, though a resize occasionally copies the list. Inserting or deleting near the front or middle takes O(n) because later references must shift.

If you often insert or remove items, compare that cost with the trade-offs of a linked list. A linked list can edit in O(1) time when you already have the node, but finding that node still takes a traversal. See array vs. linked list trade-offs.

Exercise: find the positions

Print the indices of temperatures above 17. enumerate gives each value and its index.

temperatures = [14, 17, 19, 16, 21]
warm_positions = [
    index
    for index, temperature in enumerate(temperatures)
    if temperature > 17
]
print(warm_positions)

Expected output:

[2, 4]

2. Add a row and column

A matrix can be represented as a list of rows. Use matrix[row][column] in that order: choose the row first, then the item within it. For example, grid[1][2] means the second row and third column.

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

print(grid[1][2])  # 6

Here’s a row-by-row traversal that totals each row:

row_totals = []
for row in grid:
    total = 0
    for value in row:
        total += value
    row_totals.append(total)

print(row_totals)

Expected output:

[6, 15, 24]

This example assumes a rectangular matrix. If you need a fresh grid of zeroes, create each row separately:

rows, columns = 2, 3
grid = [[0] * columns for _ in range(rows)]
grid[0][1] = 5
print(grid)

Expected output:

[[0, 5, 0], [0, 0, 0]]

Avoid [[0] * columns] * rows: that repeats the same inner list, so changing one row changes them all. Python’s nested lists are separate list objects; treat row and column as coordinates, not as a promise about one flat block of memory.

Exercise: total one column

Use the same row-then-column order to add the values in column 1:

matrix = [[2, 4, 6], [1, 3, 5]]
column_total = sum(matrix[row][1] for row in range(len(matrix)))
print(column_total)

Expected output:

7

3. Move a two-pointer window

A sliding window tracks a contiguous section of a list. One pointer marks its left edge; the loop’s right index extends the other edge. When the total gets too large, move left forward until the window fits again.

The example assumes non-negative values and a non-negative limit. With negative values, extending a window can lower its sum, so this shrinking rule no longer guarantees the longest valid window.

Exercise: longest window with a limited sum

Find the longest contiguous window whose sum is at most limit. The function returns its length and inclusive index bounds.

def longest_window_at_most(values, limit):
    left = 0
    current_sum = 0
    best_length = 0
    best_bounds = None

    for right, value in enumerate(values):
        current_sum += value

        while current_sum > limit:
            current_sum -= values[left]
            left += 1

        length = right - left + 1
        if length > best_length:
            best_length = length
            best_bounds = (left, right)

    return best_length, best_bounds


values = [2, 1, 3, 2, 1, 1]
print(longest_window_at_most(values, 6))

Expected output:

(3, (0, 2))

Indices 0 through 2 contain [2, 1, 3], which has length 3 and sum 6. Both pointers move only forward, so the scan takes O(n) time and O(1) extra space. The input list is not copied or changed.

A short practice path

Try these in order:

  1. Change the first exercise to print positions whose temperatures are below 17. Expected: [0, 3].
  2. Change the matrix exercise to total column 2. Expected: 11.
  3. In the sliding-window exercise, change limit to 4. The longest window has length 3 at indices (3, 5), containing [2, 1, 1].

The window trick depends on the condition staying predictable as the boundaries move. Here, non-negative values let us discard items from the left until the sum fits. If that guarantee is missing, look for a different approach.

Category

Related Posts

Arrays vs Linked Lists: Understanding the Trade-offs

Compare arrays and linked lists by access, edits, memory use, and cache behavior, with one operation matrix and a reproducible benchmark for real workloads.

#arrays #linked-lists #data-structures

Sliding Window: Dynamic Subarray Problems

Solve maximum subarray, longest substring, and subarray average problems with O(n) time using the sliding window technique.

#sliding-window #algorithms #data-structures

Two Pointers Technique: Efficient Array Traversal

Master the two pointers technique for O(1) space complexity solutions to array problems like pair sum, palindrome check, and triplet finding.

#two-pointers #algorithms #data-structures