- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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]
Advertisements