
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Explain Python Matrix with examples
A matrix in Python is a two-dimensional array having a specific number of rows and columns. The data elements in Python matrix can be numbers, strings or symbols etc.
Matrix or two-dimensional list is an important data structure. Various operations associated with matrix involve transpose, addition or multiplication of two matrices.
We will discuss how to declare a matrix in python with a specific number of rows and columns and then input data items from the user and finally print the matrix.
Declare a matrix in Python as nested list
A matrix in Python can be declared as a nested list. The number of rows and columns needs to be specified. Suppose number of rows is 3 and number of columns is 4. We will declare the matrix as follows
Matrix=[[0]*4 for i in range(3)]
Input matrix elements and print them row-wise
Example
col=4 rows=3 matrix=[[0]*col for i in range(rows)] for i in range(rows): print("Enter","row",i+1,"elements") for j in range(col): matrix[i][j]=int(input()) def rowvise(matrix): for i in range(rows): print(matrix[i]) print("print as nested list") print(matrix) print("print each row in separate line") rowvise(matrix)
Output
Enter row 1 elements 1 2 3 4 Enter row 2 elements 5 6 7 8 Enter row 3 elements 1 2 3 4 print as nested list [[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]] print each row in separate line [1, 2, 3, 4] [5, 6, 7, 8] [1, 2, 3, 4]
These are the basic operations on matrix, which involve declaring a matrix, assigning data element values and printing a matrix. The other operations such as transpose can be achieved by applying specific logic to the given matrix.
- Related Articles
- Explain Stack in Python with examples
- What is Queue in Python? Explain with examples
- What is an object in Python? Explain with examples
- Explain 5NF with examples in DBMS
- Explain Chosen and Select2 with Examples
- Explain \'Haploid\' and \'Diploid\' With Examples
- What is JavaScript closure? Explain with examples.
- Explain JavaScript Regular Expression modifiers with examples
- What are Synthetic Fibres? Explain with examples.
- Explain some properties of compounds with examples.
- Explain fractions and their types with examples.
- What are natural fibres? Explain with examples.
- Explain about EventHandler with Examples in JavaScript
- Timeit in Python with Examples?
- Explain the finally Statement in JavaScript with examples.
