You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二维列表复制答疑:如何正确复制4×4网格列表

Great question—since you're working with a 2D list (your 4×4 grid), the shallow copy methods that work for 1D lists (like list(l1) or l1[:]) won't fully break the reference association. Here's why, plus the reliable ways to create a true independent copy:

Why Shallow Copies Fail for 2D Lists

A 2D list is a list of lists. When you do a shallow copy (e.g., copied_grid = original_grid[:]), you're creating a new outer list—but each row inside that new list is still a reference to the rows in the original grid. Modifying any element inside a row of the original grid will also change the copied grid, because they share the same inner list references.

Reliable Methods to Copy Your 4×4 Grid

1. List Comprehension (Most Pythonic for 2D Grids with Immutable Elements)

Since your grid contains numbers (immutable values), you can copy each row individually with a slice or list():

# Original 4×4 grid
original_grid = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

# Copy using list comprehension + row slicing
copied_grid = [row[:] for row in original_grid]

# OR: Use list() to copy each row
copied_grid = [list(row) for row in original_grid]

This creates a new outer list, and a new copy of each inner row—so there's no shared reference between original_grid and copied_grid.

2. copy.deepcopy() (Universal Solution for Any Nested Depth)

If you ever need to copy a grid with deeper nesting (e.g., 3D lists) or mutable elements inside rows, use deepcopy from the copy module. It recursively copies all nested objects:

import copy

original_grid = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

copied_grid = copy.deepcopy(original_grid)

This is the most foolproof method, as it works regardless of how deeply your list is nested.

Verify the Copy Works

To confirm the copies are independent, modify the original grid and check the copied one:

# Change an element in the original grid
original_grid[0][0] = 99

print(original_grid[0][0])  # Output: 99
print(copied_grid[0][0])    # Output: 1 (no change—success!)

内容的提问来源于stack exchange,提问作者V. Raman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:06:29