#!/usr/bin/python3 # -*- coding: utf-8 -*- from typing import List # %% Creating and enumerating 2D lists # You can do this manually: tictactoe: List[List[str]] = [["x", "o", "x"], [" ", "x", "x"], ["o", "o", " "]] print(tictactoe) print("First row is", tictactoe[0]) print("Second row is", tictactoe[1]) print("First row second col is", tictactoe[0][1]) print("Second row second col is", tictactoe[1][1]) # ... if you don't want to use a numpy array for some reason. rows: int = 2 cols: int = 3 # We can make an array like this (ok) print([0] * 4) # This below does NOT do what you think, # and is likely WRONG for what you want! # It's a single array, referenced multiple times: mybadarray: List[List[int]] = [[0] * cols] * rows mybadarray[0][0] = 5 print(mybadarray) # This works too (more beginner-friendly) arr: List[List[int]] = [] for i in range(rows): arr.append([0] * cols) arr[0][2] = 5 print(arr) # This is what you want, different sub-arrays: # only if inside element is immutable, does the []*num work. # because assignment just overwrites # []*num is a shallow copy, but when element is immutable, # assignment overwrites each uniquely. arr = [[0] * cols for i in range(rows)] arr[0][2] = 5 print(arr) # This works too: rows = 5 cols = 3 arr = [] for i in range(rows): arr.append([]) for j in range(cols): arr[i].append(0) print(arr) # arrays are indexed[down][over] starting at 0, from the top left # arrays are indexed[row][col] starting at 0, from the top left # This is the 2nd column on the top row! arr[0][1] = 1 # This is the 2nd row on the first column arr[1][0] = 2 # Output (3 examples) for row in arr: print(row) # With a separator for row in arr: print(*row, sep="|") # Explicit loops for row in arr: print("|", sep="", end="") for char in row: print(char, "|", sep="", end="") print() # Explicit indexing (more c-style) for irow in range(len(arr)): for icol in range(len(arr[irow])): print(arr[irow][icol], end=" ") print() # Input, where this can be nested in a for loop, like just above # A character at a time: arr[irow][icol] = int(input()) # A row at a time arr[irow] = list(map(int, input().split())) # NOTE: # For many things, python 2D Lists are sufficient/good. # There's a better way to do n-D arrays for processing numerical data, numpy: # Documentation: https://numpy.org/doc/stable/ import numpy as np help(np)