Work with two -dimensional arrays in Python: creation, access to elements and manipulations with matrices and data tables.

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Creating two-dimensional arrays in Python

Two-dimensional arrays in Python are lists of lists, where each nested list is a row of a matrix. This data structure is widely used for working with matrices, tables, and two-dimensional coordinate systems.

Static creation of a two-dimensional array

The easiest way to create a two-dimensional array is to declare it explicitly:

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

Creating an empty two-dimensional array

A list generator is used to create an empty two-dimensional fixed-size array:

 

rows, cols = 3, 3
matrix = [[0 for _ in range(cols)] for _ in range(rows)]
print(matrix)  # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Important: Avoid creating an array using [[0] * cols] * rows, as this will create references to the same object.

Initialization with the specified value

rows, cols = 3, 3
initial_value = 1
matrix = [[initial_value for _ in range(cols)] for _ in range(rows)]
print(matrix)  # [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

Creation from a string

A useful way to create a two-dimensional array from a formatted string:

input_string = "1,2,3 4,5,6 7,8,9"
rows = input_string.split(' ')
two_dimensional_array = [list(map(int, row.split(','))) for row in rows]
print(two_dimensional_array)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Creating using NumPy

For more complex operations, we recommend using the NumPy library:

import numpy as np

# Creating a null array
matrix = np.zeros((3, 3))

# Creating a unit matrix
identity = np.eye(3)

# Create from a regular list
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Access to the elements of a two-dimensional array

Reading the element

Double indexing is used to access the element:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][2]) # 6 ( second line, third element)

Changing the element

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
matrix[1][2] = 10
print(matrix)  # [[1, 2, 3], [4, 5, 10], [7, 8, 9]]

Getting a row or column

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

# Getting the row
row = matrix[1] # [4, 5, 6]

# Getting column
column = [row[1] for row in matrix]  # [2, 5, 8]

Iterating over a two-dimensional array

Iterating over lines

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

for row in matrix:
    print(row)

Iterating over elements with indexes

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

for i in range(len(two_dimensional_array)):
for j in range(len(two_dimensional_array[i])):
print(f"The element at position ({i}, {j}) is equal to {two_dimensional_array[i][j]}")

Iterating with enumerate

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

for i, row in enumerate(matrix):
    for j, element in enumerate(row):
        print(f"matrix[{i}][{j}] = {element}")

Basic operations with two-dimensional arrays

Matrix transposition

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

transposed = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print(transposed)  # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

# Alternative way with zip
transposed = list(map(list, zip(*matrix)))

Search for the maximum and minimum element

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

max_value = max(max(row) for row in matrix)
min_value = min(min(row) for row in matrix)
print(f"Maximum element: {max_value}")  #9
print(f"Minimum element: {min_value}")  # 1

Sum of all elements

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

total_sum = sum(sum(row) for row in matrix)
print(f"Sum of all elements: {total_sum}")  # 45

Sum by rows and columns

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

#
row_sums row sum = [sum(row) for row in matrix]
print(f"Row sum: {row_sums}")  # [6, 15, 24]

# Sum by columns
col_sums = [sum(matrix[i][j] for i in range(len(matrix))) for j in range(len(matrix[0]))]
print(f"Sum by columns: {col_sums}")  # [12, 15, 18]

Two-dimensional array generators

Generating a matrix of products

rows, cols = 3, 3
matrix = [[i * j for j in range(cols)] for i in range(rows)]
print(matrix)  # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Chessboard generation

rows, cols = 3, 3
matrix = [[(i + j) % 2 for j in range(cols)] for i in range(rows)]
print(matrix)  # [[0, 1, 0], [1, 0, 1], [0, 1, 0]]

Generating a unit matrix

size = 3
identity = [[1 if i == j else 0 for j in range(size)] for i in range(size)]
print(identity)  # [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Useful functions for working with two-dimensional arrays

Checking the square matrix

def is_square(matrix):
    return len(matrix) == len(matrix[0]) if matrix else False

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(is_square(matrix))  # True

Rotation of the matrix by 90 degrees

def rotate_90(matrix):
    return [[matrix[j][i] for j in range(len(matrix)-1, -1, -1)] for i in range(len(matrix[0]))]

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotated = rotate_90(matrix)
print(rotated)  # [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Smoothing a two-dimensional array

def flatten(matrix):
    return [element for row in matrix for element in row]

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = flatten(matrix)
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Two-dimensional arrays in Python provide a flexible tool for working with tabular data and matrices. For more complex mathematical operations, it is recommended to use specialized libraries such as NumPy or Pandas.

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base