close

How do I make a grid in python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I make a grid in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I make a grid in python?

  1. How do I make a grid in python?

    This for loop appends the same row list to the grid list (actually it appends 5 different references to the same list).

  2. make a grid in python

    This for loop appends the same row list to the grid list (actually it appends 5 different references to the same list).

Method 1

Use list()

gridline = []
for i in range(5):
    gridline.append("")
grid = []
for i in range(5):
    grid.append(list(gridline))

Method 2

for i in range(height):
    grid.append(row)

This for loop appends the same row list to the grid list (actually it appends 5 different references to the same list).

Instead, you should append a new, different list:

for i in range(height):
    grid.append([])

Verify by viewing the memory addresses of the inner lists in these 2 examples:

grid = []
row = []
for i in range(5):
    grid.append(row)
for li in grid:
    print(id(li))
# 92532104
# 92532104
# 92532104
# 92532104
# 92532104

compared to

grid = []
for i in range(5):
    grid.append([])
for li in grid:
    print(id(li))

# 80801224
# 80801160
# 80669704
# 80381192
# 80380488

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read