Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Boolean list initialization - Python
Next article icon

Initialize Matrix in Python

Last Updated : 19 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

There are many ways to declare a 2 dimensional array with given number of rows and columns. Let us look at some of them and also at the small but tricky catches that accompany it. 
We can do it using list comprehension, concatenation feature of * operator and few other ways.

Method 0: 2 list comprehensions

Python3




rows = 3
cols = 2
 
mat = [[0 for _ in range(cols)] for _ in range(rows)]
print(f'matrix of dimension {rows} x {cols} is {mat}')
 
# editing the individual elements
mat[0][0], mat[0][1] = 1,2
mat[1][0], mat[1][1] = 3,4
mat[2][0], mat[2][1] = 5,6
print(f'modified matrix is {mat}')
 
# checking the memory address of first element of a row
print(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')
print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')
print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
 
 
Output
matrix of dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[1, 2], [3, 4], [5, 6]] addr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336 addr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464 

Method 1: 1 list comprehension  inside and  1 concatenation operation outside

Python3




rows = 3
cols = 2
 
mat = [[0 for _ in range(cols)]]*rows
print(f'matrix with dimension {rows} x {cols} is {mat}')
 
# editing the individual elements
mat[0][0], mat[0][1] = 1,2
mat[1][0], mat[1][1] = 3,4
mat[2][0], mat[2][1] = 5,6
print(f'modified matrix is {mat}')
 
# checking the memory address of first element of a row
print(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')
print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')
print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
 
 
Output
matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[5, 6], [5, 6], [5, 6]] addr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464 addr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464 

Method 2: 1 list comprehension  outside and  1 concatenation operation inside

Python3




rows = 3
cols = 2
 
mat = [[0]*cols for _ in range(rows)]
print(f'matrix with dimension {rows} x {cols} is {mat}')
 
# editing the individual elements
mat[0][0], mat[0][1] = 1,2
mat[1][0], mat[1][1] = 3,4
mat[2][0], mat[2][1] = 5,6
print(f'modified matrix is {mat}')
 
# checking the memory address of first element of a row
print(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')
print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')
print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
 
 
Output
matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[1, 2], [3, 4], [5, 6]] addr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336 addr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464 

Method 3: 2 concatenation operations

Python3




rows = 3
cols = 2
 
mat = [[0]*cols]*rows
print(f'matrix with dimension {rows} x {cols} is {mat}')
 
# editing the individual elements
mat[0][0], mat[0][1] = 1,2
mat[1][0], mat[1][1] = 3,4
mat[2][0], mat[2][1] = 5,6
print(f'modified matrix is {mat}')
 
# checking the memory address of first element of a row
print(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')
print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')
print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
 
 
Output
matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]] modified matrix is [[5, 6], [5, 6], [5, 6]] addr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464 addr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464 addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464 

Here we can see that output of Method 1 & Method 3 are *unexpected*. 

We expected all rows in mat to be all different after we assigned them with 1,2,3,4,5,6 respectively. But in Method1 & Method3 they are all equal to [5,6]. This shows that essentially mat[0],mat[1] & mat[2] are all referencing the same memory which can further be seen by checking their addresses using the id function in python. 

 Hence be very careful while using (*)  operator. 

To understand it further we can use 3 dimensional arrays to and there we will have 2^3 possibilities of arranging list comprehension and concatenation operator.  This is an exercise I leave for the reader to perform.

If working with numpy then we can do it using reshape method.

Python3




import numpy as np
 
rows = 3
cols = 2
size = rows*cols
 
mat = np.array([0]*size).reshape(rows,cols)
 
 


Next Article
Boolean list initialization - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python matrix-program
Practice Tags :
  • python

Similar Reads

  • Python - K Matrix Initialization
    Sometimes in the world of competitive programming, we need to initialise the matrix, but we don’t wish to do it in a longer way using a loop. We need a shorthand for this. This type of problem is quite common in dynamic programming domain. Let’s discuss certain ways in which this can be done. Method
    5 min read
  • Python - Initialize dictionary keys with Matrix
    Sometimes, while working with Python Data, we can have a problem in which we need to construct an empty mesh of dictionaries for further population of data. This problem can have applications in many domains which include data manipulation. Let's discuss certain ways in which this task can be perfor
    4 min read
  • Python Initialize List of Lists
    A list of lists in Python is often used to represent multidimensional data such as rows and columns of a matrix. Initializing a list of lists can be done in several ways each suited to specific requirements such as fixed-size lists or dynamic lists. Let's explore the most efficient and commonly used
    3 min read
  • Boolean list initialization - Python
    We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True or False. Let's explore several ways to initialize a boolean list in Python. Using List MultiplicationThe most efficient way to initialize a boolean list with identical values
    3 min read
  • Python | Row lengths in Matrix
    The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + m
    4 min read
  • Python - Incremental Range Initialization in Matrix
    Sometimes, while working with Python, we can have a problem in which we need to perform the initialization of Matrix. Simpler initialization is easier. But sometimes, we need to perform range incremental initialization. Let's discuss certain ways in which this task can be performed. Method #1: Using
    4 min read
  • Python - Incremental K sized Row Matrix Initialization
    Sometimes, while working with Python, we can have a problem in which we need to perform initialization of matrix with Incremental numbers. This kind of application can come in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing Th
    6 min read
  • Python - Convert Matrix to Dictionary
    The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
    4 min read
  • Python | Custom length Matrix
    Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this. Method #1: Using zip() + list comprehensio
    6 min read
  • How to Initialize a String in Python
    In Python, initializing a string variable is straightforward and can be done in several ways. Strings in Python are immutable sequences of characters enclosed in either single quotes, double quotes or triple quotes. Let’s explore how to efficiently initialize string variables. Using Single or Double
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences