# How to Make a 4×4 Magic Square in Python

Magic Squares are one of the oldest recreational mathematics games. The smallest magic squares are three by three, but they can be made up to any size with the right formulas. Odd and even ordered magic squares have different formulas, but can be easily generated. Programming has made it even easier to make magic squares, as we are about to see. Let’s make a 4×4 Magic Square in Python

In this post, we’ll learn about:

• What is a Magic Square?
• How Do You Create a 4×4 Magic Square?
• The Five Binary Encoding Patterns for 4×4 Magic Squares
• Python Code to Make a 4 by 4 Magic Square
• Creating the Magic Square with Lists in Python
• Full Code for Python 4×4 Magic Square
• Testing Our Python Magic Square
• Summary of Creating a 4×4 Magic Square in Python

## What is a Magic Square?

A magic square is a square that is filled with numbers, usually positive integers, such that the rows, diagonals, and columns of the square all add up to the same number.

## How Do You Create a 4×4 Magic Square?

Odd and even rank magic squares are created with different formulas. The 4×4 even rank magic square is created using five binary encoded patterns. A binary encoded pattern is an overlay of the square in which each square contains either a 0 or a 1. Let’s take a look at what the patterns for the 4×4 magic square are.

## The Five Binary Encoding Patterns for 4×4 Magic Squares

These are the five binary encoding patterns that we add up to make a 4×4 magic square.

If you layer these patterns you get the square below. This base 4×4 magic square adds up to 12 in every row, column, and diagonal.

## Python Code to Make a 4 by 4 Magic Square

Now we know what a magic square is and what the basic 4×4 magic square looks like. Let’s use Python to create some 4×4 magic squares. We will use nested lists to represent our magic square and its binary encoded patterns. We don’t need any external Python libraries to create this function.

### Creating the Magic Square with Lists in Python

The first thing we’re going to do is create a function to generate the magic square.Our function will create the five binary encoded patterns separately and has one parameter. The only parameter this function takes is a list, representing the values for each binary encoding pattern. For example, a list of 8, 4, 2, 1, 1 would yield the patterns below.

These patterns will yield the following magic square with value 34.

The first thing we’re going to do in our function is create an empty nested list representation of all five patterns.

``````def create_square(params: list):
patterns = [[None] for _ in range(5)]``````

Now let’s get started on creating the individual patterns.

### First Magic Square Pattern in Python

Let’s implement the first pattern. Remember that we are implementing the square pattern as a nested list. This means that each row of the square should be represented as a list. There are only two different row patterns in this pattern, so we’ll create two lists that represent each pattern.

We use the first element of the parameter list to scale the binary pattern and create the square pattern using list comprehension on the two list patterns we created earlier.

``````   '''
pattern 1
0011
1100
0011
1100
'''
pattern_1_1 = [0, 0, 1, 1]
pattern_1_2 = [1, 1, 0, 0]
patterns = [[pattern*params for pattern in pattern_1_1],
[pattern*params for pattern in pattern_1_2],
[pattern*params for pattern in pattern_1_1],
[pattern*params for pattern in pattern_1_2]]``````

### Second Magic Square Pattern in Python

Our second magic square pattern will also need two different row patterns. Just like the first square pattern, we will create the two row patterns with lists. Then, we’ll create the square pattern using list comprehension to scale the patterns by the second entry in the parameters list.

``````   '''
pattern 2
0110
1001
0110
1001
'''
pattern_2_1 = [0, 1, 1, 0]
pattern_2_2 = [1, 0, 0, 1]
patterns = [[pattern*params for pattern in pattern_2_1],
[pattern*params for pattern in pattern_2_2],
[pattern*params for pattern in pattern_2_1],
[pattern*params for pattern in pattern_2_2]]``````

### Third Magic Square Pattern in Python

Our third magic square pattern is built in the same way as the first two. First, we’ll create another two list representations of the row pattern representations. Next, we use the third entry from the parameter list to scale these row patterns into the third magic square pattern.

``````   '''
pattern 3
0101
0101
1010
1010
'''
pattern_3_1 = [0, 1, 0, 1]
pattern_3_2 = [1, 0, 1, 0]
patterns = [[pattern*params for pattern in pattern_3_1],
[pattern*params for pattern in pattern_3_1],
[pattern*params for pattern in pattern_3_2],
[pattern*params for pattern in pattern_3_2]]``````

### Fourth Magic Square Pattern in Python

The process to create the first three magic square patterns has been almost the same. For the fourth one, we don’t need to recreate row patterns. We are simply reusing the row patterns that the third magic square uses in a different order and scaling by the fourth entry of the parameters instead of the third.

``````   '''
pattern 4
0101
1010
1010
0101
'''
patterns = [[pattern*params for pattern in pattern_3_1],
[pattern*params for pattern in pattern_3_2],
[pattern*params for pattern in pattern_3_2],
[pattern*params for pattern in pattern_3_1]]``````

### Fifth Magic Square Pattern in Python

This one is even easier than the fourth pattern. All we do here is create a matrix of ones and then scale by the fifth and last entry of the parameters list.

``````   '''
pattern5
1111
1111
1111
1111
'''
patterns = [[params for _ in range(4)] for _ in range(4)]``````

### Layering the Patterns into a Magic Square

Now that we have all five patterns created, we need to layer them together to create the magic square. To start off, we’ll create a magic square of all zeros. Then we’ll loop through the list of patterns and add each entry of each pattern to the corresponding entry in the magic square. Finally, we’ll return the square we created.

``````   square = [[0 for _ in range(4)] for _ in range(4)]
for pattern in patterns:
for i in range(4):
for j in range(4):
square[i][j] += pattern[i][j]
return square``````

## Full Code for Python 4×4 Magic Square Generator Function

That concludes the function to create a 4×4 magic square generator in Python. This is the full code for the `create_square` function.

``````def create_square(params: list):
patterns = [[None] for _ in range(5)]
'''
pattern 1
0011
1100
0011
1100
'''
pattern_1_1 = [0, 0, 1, 1]
pattern_1_2 = [1, 1, 0, 0]
patterns = [[pattern*params for pattern in pattern_1_1],
[pattern*params for pattern in pattern_1_2],
[pattern*params for pattern in pattern_1_1],
[pattern*params for pattern in pattern_1_2]]
'''
pattern 2
0110
1001
0110
1001
'''
pattern_2_1 = [0, 1, 1, 0]
pattern_2_2 = [1, 0, 0, 1]
patterns = [[pattern*params for pattern in pattern_2_1],
[pattern*params for pattern in pattern_2_2],
[pattern*params for pattern in pattern_2_1],
[pattern*params for pattern in pattern_2_2]]
'''
pattern 3
0101
0101
1010
1010
'''
pattern_3_1 = [0, 1, 0, 1]
pattern_3_2 = [1, 0, 1, 0]
patterns = [[pattern*params for pattern in pattern_3_1],
[pattern*params for pattern in pattern_3_1],
[pattern*params for pattern in pattern_3_2],
[pattern*params for pattern in pattern_3_2]]
'''
pattern 4
0101
1010
1010
0101
'''
patterns = [[pattern*params for pattern in pattern_3_1],
[pattern*params for pattern in pattern_3_2],
[pattern*params for pattern in pattern_3_2],
[pattern*params for pattern in pattern_3_1]]
'''
pattern5
1111
1111
1111
1111
'''
patterns = [[params for _ in range(4)] for _ in range(4)]
square = [[0 for _ in range(4)] for _ in range(4)]
for pattern in patterns:
for i in range(4):
for j in range(4):
square[i][j] += pattern[i][j]
return square``````

## Testing Our Python 4×4 Magic Square Generator

Now that we’ve made a magic square generator, let’s test our function. We will pass the parameters a list of `[8, 4, 2, 1, 1]` which should result in the magic square we showed right before the code.

``````sq = create_square([8, 4, 2, 1, 1])
for l in sq:
print(l)``````

The printout from running this file with Python should look like the image below. This is the same 34 magic square we showed above. Feel free to play around with the entries in your parameter list to generate different magic squares.

## Summary of Creating a 4×4 Magic Square in Python

In this post we covered how to create a 4×4 magic square in Python. First, we covered some background information on magic squares. Magic squares are `n` by `n` squares filled with numbers. Each row, column, and diagonal adds to the same magic number.

Next, we covered the five binary encoding patterns involved in creating a 4×4 magic square before diving into the Python code. We created a function that takes one list of five parameters and makes a magic square. Each of the five parameters correspond to how we scale the patterns. We represented the five magic square patterns involved in making a 4×4 magic square as nested lists.

To finish off our magic square creation function, we create a matrix of 0s to represent the initial square and populate the square using the five magic patterns we created. Finally, we tested our magic square creator function and saw that it generated a magic square of 34 as predicted.

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$