- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Using 2D arrays/lists the right way
Python provides many ways to create 2-dimensional lists/arrays. However, one must know the differences between these ways because they can create complications in code that can be very difficult to trace out.
Example
rows, cols = (5, 5) arr = [[0]*cols]*rows #lets change the first element of the 1st row to 1 & print the array arr[0][0] = 1 for row in arr: print(row) arr = [[0 for i in range(cols)] for j in range(rows)] #again in this new array lets change the 1st element of the first row # to 1 and print the array arr[0][0] = 1 for row in arr: print(row)
Output
[1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0]
- Related Articles
- C++ Program to Represent Graph Using 2D Arrays
- Review the Right Way!
- Why you should use NumPy arrays instead of nested Python lists?
- Sum 2D array in Python using map() function
- The easiest way to concatenate two arrays in PHP?
- What is the simplest way to SSH using Python?
- How to loop through multiple lists using Python?
- What is right way to save the natural world?
- What is the best way to get stock data using Python?
- What is the Best Way to Develop Desktop Applications Using Python?
- Merging two arrays in a unique way in JavaScript
- How to Perform Numpy Broadcasting using Python using dynamic arrays?
- Merge two sorted arrays in Python using heapq?
- Updating Lists in Python
- Simple way to find if two different lists contain exactly the same elements in Java

Advertisements