Print 2D Array - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Print 2D Array (/thread-15433.html) |
Print 2D Array - dragu_stelian - Jan-17-2019 Hello! I am new in Python and I have a question. In the next code I want to print a 2D array in "C++ style" tab = [[]] rows = int(input("Enter size of the rows: ")) cols = int(input("Enter size of the cols: ")) for i in range(0, rows): for j in range(0, cols): arr = int(input("tab[{}][{}] = ".format(i,j))) tab.append(arr) print() for i in range(len(tab)): print(tab[i], end = " ") print()For a tab[2][3] the below code will print: Enter size of the rows: 2 Enter size of the cols: 3 tab[0][0] = 11 tab[0][1] = 12 tab[0][2] = 13 tab[1][0] = 21 tab[1][1] = 22 tab[1][2] = 23 [] 11 12 13 21 22 23 Why square brackets at the beginning ? There are many ways to print the 2D array in Python ? RE: Print 2D Array - buran - Jan-17-2019 To answer your question - on line 1 you initialize the tab list with empty list, i.e. your tab list already has 1 element before you input rest values and append them to tab list. make line 1 tab = []However I don't think the result is what you expect - tab is a list, not list of lists if that is what you expect RE: Print 2D Array - perfringo - Jan-17-2019 What datastructure you want to build? I assume that 2D array is list of lists (matrix). If so, you can create in several ways. Some examples: >>> matrix = [] # create empty list named matrix >>> for i in range(3): ... matrix.append([]) # append empty list to end of matrix ... for j in range(4): ... matrix[-1].append(0) # append zeros to last list of matrix ... >>> print(matrix) [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] # matrix with three rows and four columnsIt can be done with list comprehension with one-liner: >>> [[0 for i in range(4)] for j in range(3)] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]Matrix with consecutive numbers with asking from user number of rows and columns: rows = int(input('Number of rows: ')) cols = int(input('Number of columns: ')) mtx = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)] print(mtx)In case of three rows and four columns this will print [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] Sometime there is need for creating matrices with random numbers in it. In these cases utility functions like below can be handy: def matrix_with_double_digits(rows, cols): return [[random.choice(range(10,100)) for i in range(cols)] for j in range(rows)]This will generate matrix with specified number of rows and columns populated with random two-digit numbers. RE: Print 2D Array - aakashjha001 - Jan-27-2019 # this is one approach to create a 2D list in python. #There are multiple ways of creating. n = int(input()) a = [] for i in range(n): row = input().split() for i in range(len(row)): row[i] = int(row[i]) a.append(row) print(a) |