SoFunction
Updated on 2025-03-10

Python implements a list generation formula for two-dimensional list

A list generation formula for a two-dimensional list allows you to generate a list where each element itself is also a list. This is very useful when dealing with matrix or tabular data.
Here is an example of how to use list generation to create a two-dimensional list:

Basic syntax

[[expression for variable in iterable] for variable in iterable]

Here, the outer layer generates rows and the inner layer generates columns.

Example

1. Create a 3x3 unit matrix

identity_matrix = [[1 if i == j else 0 for i in range(3)] for j in range(3)]
print(identity_matrix)
# Output:# [[1, 0, 0],
#  [0, 1, 0],
#  [0, 0, 1]]

2. Create a 4x4 multiplication table

multiplication_table = [[i * j for i in range(1, 5)] for j in range(1, 5)]
print(multiplication_table)
# Output:# [[1, 2, 3, 4],
#  [2, 4, 6, 8],
#  [3, 6, 9, 12],
#  [4, 8, 12, 16]]

3. Create a 5x5 diagonal matrix (the elements on the diagonal are 1 and the rest are 0)

diagonal_matrix = [[1 if i == j or i + j == 4 else 0 for i in range(5)] for j in range(5)]
print(diagonal_matrix)
# Output:# [[1, 0, 0, 0, 1],
#  [0, 1, 0, 1, 0],
#  [0, 0, 1, 0, 0],
#  [0, 1, 0, 1, 0],
#  [1, 0, 0, 0, 1]]

Practical

# Create a 2D listlst = [
    ['City', 'Monopoly', 'Year-to-year'],
    ['Beijing', 102, 103],
    ['Shanghai', 104, 504],
    ['Shenzhen', 100, 39]
]
print(lst)

for row in lst:
    for item in row:
        print(item, end='\t')
    print()

# List generation formula generates a 2D list of 4 rows and 5 columnslst2 = [[j for j in range(5)] for i in range(4)]
print(lst2)

This is the end of this article about python implementing list generation forms for two-dimensional lists. For more related content for list generations for python two-dimensional lists, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!