The ChessAIThon project (2025-1-ES01-KA220-VET-000354329) is co-funded by the European Union. The views and opinions expressed in this publication are those of the author(s) only and do not necessarily reflect those of the European Union or the Spanish Service for the Internationalisation of Education (SEPIE). Neither the European Union nor the National Agency SEPIE can be held responsible for them.
Table of Contents
A chessboard is an 8x8 grid. If we had to create a separate variable for every square (square_a1, square_a2... square_h8), we would have 64 distinct variables that are impossible to manage. This is where data structures come in.
The List (1D Array)
Consider a single horizontal row of the chessboard (called a "rank"). We can represent it as a list. A list is an ordered sequence of elements.
Python
# Representing Rank 2 (White Pawns)
rank_2 = ["P", "P", "P", "P", "P", "P", "P", "P"]
In Python, we define a list by enclosing a sequence of elements in square brackets [] separated by commas. Lists are ordered, indexed (starting at 0), and mutable (changeable).
Let's look at some common operations and properties of lists:
my_list = [] # empty list
primes = [2, 3, 5, 7] # numerical list
rank_2 = ["P", "P", "P", "P", "P", "P", "P", "P"] # list of strings
my_list = [1, "hello", 3.14] # mixed list (heterogeneous)
# Accessing elements
print(my_list[0]) # prints the first element of the list;
# the first element always has index 0
# Useful operations
rank_2 = ["P"] * 8 # assignment of 8 identical elements to the list
my_list.append("x") # adds an element to the end of the list
# Measuring and Slicing
print(len(rank_2)) # displays the length (number of elements) of a list
print(rank_2[0:2]) # prints the first two elements of the list (slicing)
The Matrix (List of Lists, 2D array)
To represent the entire board, we join the rows. A chessboard is a "list of rows." In computer science, this is called a matrix or 2D array. To access a specific square in a matrix, we use two coordinates: [row][column].
Let's look at some operations and properties of matrices:
# A 3x3 matrix – a square matrix
matrix = [[1, 2, 3], [2, 1, 0], [1, 1, 1]]
# Assignment: assign a new value to the element at position 0,0 (the first one)
matrix[0][0] = 3
# Display the entire matrix
print(matrix)
# Display a specific element of the matrix (Row 1, Column 2)
print(matrix[1][2])
The Indexing Problem (0 vs 1):
This requires a mental translation: