Search code examples
pythonlisttabular

Alternating 1's and 0's in a table - Python


I want to make a table of alternating 1's and 0's using for statements and lists for a given number of rows and columns (similar to the code below). Any ideas as to how I would do this?

#fill elements in left and right columns with ones

ROWS = m
COLUMNS = n
table = []

for i in range(COLUMNS):
    if i ==0 or i == (COLUMNS-1):
        column = [1] * ROWS
    else:
        column = [0] * ROWS
    table.append(column)

for i in range(ROWS):
    for j in range(COLUMNS):
        print(table[j][i], end=" ")
    print()

Solution

  • Maybe you want something like this:

    ROWS = 5
    COLUMNS = 5
    table = [[1 if i%2==0 else 0 for i in range(COLUMNS)] for j in range(ROWS)]
    
    for row in table:
    for cell in row:
        print (cell, end=' ')
    print()
    1 0 1 0 1
    1 0 1 0 1
    1 0 1 0 1
    1 0 1 0 1
    1 0 1 0 1
    

    OR maybe:

    table = [[(i+j)%2 for i in range(COLUMNS)] for j in range(ROWS)]
    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