create a list of lists with a checkerboard pattern

Question:

I would like to change the values ​​of this list by alternating the 0 and 1 values ​​in a checkerboard pattern.

table =  

1       1       1       1       1
1       1       1       1       1
1       1       1       1       1
1       1       1       1       1
1       1       1       1       1

i tried:

for i in range(len(table)):
    for j in range(0, len(table[i]), 2): # ho definito uno step nella funzione range
            table[i][j] = 0 

but for each list the count starts again and the result is:


       0       1       0       1       0
       0       1       0       1       0
       0       1       0       1       0
       0       1       0       1       0
       0       1       0       1       0

my question is how can I change the loop to form a checkerboard pattern.

I expect the result to be like:

       0       1       0       1       0
       1       0       1       0       1
       0       1       0       1       0
       1       0       1       0       1
       0       1       0       1       0
Asked By: Paolo Carossa

||

Answers:

for i in range(len(table)):
    for j in range(len(table[i])):
        if (i+j)%2 == 0:
            table[i][j] = 0

output:

 [[0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0]]
Answered By: JayPeerachai

There doesn’t appear to be any reliance on the original values in the list. Therefore it might be better to implement something that creates a list in the required format like this:

def checkboard(rows, columns):
    e = 0
    result = []
    for _ in range(rows):
        c = []
        for _ in range(columns):
            c.append(e)
            e ^= 1
        result.append(c)
    return result
    
print(checkboard(5, 5))
print(checkboard(2, 3))
print(checkboard(4, 4))

Output:

[[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]
[[0, 1, 0], [1, 0, 1]]
[[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]]
Answered By: Cobra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.