Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to declare, initialize and print a matrix in Python

6 Answers

0 votes
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

for n in matrix:
    print(n)
 
'''
run:
 
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
 
'''

 



answered May 31, 2017 by avibootz
0 votes
matrix = []
for i in range(0, 3 + 1):
    row = []
    for j in range(1, 4 + 1):
        row.append(i * j)
    matrix.append(row)

for n in matrix:
    print(n)
 
'''
run:
 
[0, 0, 0, 0]
[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
 
'''

 



answered May 31, 2017 by avibootz
0 votes
matrix = [[1 for i in range(10)] for j in range(10)]

for n in matrix:
    print(n)
 
'''
run:
 
[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, 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]
[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, 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]
 
'''

 



answered May 31, 2017 by avibootz
0 votes
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

print('\n'.join([''.join(['{:3}'.format(item) for item in row]) for row in matrix]))
 
'''
run:
 
  1  2  3
  4  5  6
  7  8  9
 
'''

 



answered May 31, 2017 by avibootz
0 votes
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

for i in range(3):
    for j in range(3):
        print('{:3}'.format(matrix[i][j]), end="")
    print()
 
'''
run:
 
  1  2  3
  4  5  6
  7  8  9
 
'''

 



answered May 31, 2017 by avibootz
0 votes
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

for row in matrix:
    for val in row:
        print('{:3}'.format(val), end="")
    print()
 
'''
run:
 
  1  2  3
  4  5  6
  7  8  9
 
'''

 



answered May 31, 2017 by avibootz

Related questions

...