Member-only story
How to Find the King’s Legal Moves in Chess With Python
A fun exercise to sharpen your brain and your code

Have you ever wondered how you can find the king’s legal moves on a chessboard with Python? Probably not, but it’s a fun exercise in jumping around in a grid made by lists.
The king can only move one square in any direction. This means it can do eight legal moves unless it is on the edge or in a corner.
I have added a challenge for you at the end as well. Are you going to take it?
In this program we’ll:
- Create a menu for the user so he/she can place a king on a board
- Print the board seen from black or white’s perspective
- Print the king’s legal moves based on where the user places his/her king
The Board

To write this program, we’ll use one class called Board
in board.py
and a main.py
to run it.
The creation of the board is quite easy but still has a very nice touch to it. I’ll use list comprehension to fill a list with eight lists (rows). These will have eight items inside (columns).
A chessboard is 8x8 squares. The rows are numbered, and columns are identified by a letter A-H.
Here’s the Class Board
def __init__(self)
- The first thing you notice is the
self._letters
list. This is simply the range of letters possible on a chessboard as strings — e.g., A-H. - The next list is
self._board_grid
. This list is empty for now and will be populated with several lists, representing rows. - The loop
for letters in self._letters:
uses list comprehension to do the following: