Skip to content
Fix Code Error

How to define a two-dimensional array?

March 13, 2021 by Code Error
Posted By: Anonymous

I want to define a two-dimensional array without an initialized length like this:

Matrix = [][]

but it does not work…

I’ve tried the code below, but it is wrong too:

Matrix = [5][5]

Error:

Traceback ...

IndexError: list index out of range

What is my mistake?

Solution

You’re technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this
“list comprehension”.

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 

You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is “y” address major, in other words, the “y index” comes before the “x index”.

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use “x” for both the inner and outer lists, and want a non-square Matrix.

Answered By: Anonymous

Related Articles

  • Can't install via pip because of egg_info error
  • What's the difference between eval, exec, and compile?
  • GLYPHICONS - bootstrap icon font hex value
  • Linear transformation and matrix multiplication…
  • IndexError: list index out of range and python
  • Grouping functions (tapply, by, aggregate) and the…
  • How do I merge two dictionaries in a single…
  • How to catch and print the full exception traceback…
  • Usage of __slots__?
  • error LNK2005: ✘✘✘ already defined in…
  • SQL JOIN and different types of JOINs
  • How to add users to Docker container?
  • Is it possible to apply CSS to half of a character?
  • How to update Python?
  • SQL query return data from multiple tables
  • How to avoid using Select in Excel VBA
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • VueJS components ref is undefined at all stages
  • Unexpected end of JSON input while parsing
  • Smart way to truncate long strings
  • How do you read a Python Traceback error?
  • Why is "1000000000000000 in range(1000000000000001)"…
  • How to create range in Swift?
  • Avoid multiple copy of data when composing objects…
  • How do I copy a range of formula values and paste…
  • What is a NullReferenceException, and how do I fix it?
  • For-each over an array in JavaScript
  • Improved way to get subsets of a list
  • SQL Server: Query fast, but slow from procedure
  • OpenCL - Approximation of Pi via Monte Carlo…
  • Install pip in docker
  • How to pull out an element to the right in…
  • Manually raising (throwing) an exception in Python
  • Max function using divide and conquer approach is…
  • Excel VBA For Each Worksheet Loop
  • How to get data records from a table into a result…
  • Python: print a generator expression?
  • using 2-dimensional arrays is faster than two of…
  • Fastest way to iterate over all the chars in a String
  • How does PHP 'foreach' actually work?
  • Excel VBA: AutoFill Multiple Cells with Formulas
  • easiest way to extract Oracle form xml format data
  • What is an IndexOutOfRangeException /…
  • In CSS Flexbox, why are there no "justify-items" and…
  • Using the result of a query to display images inside…
  • how to print greatest sum each rows in python?
  • Python Dictionary Comprehension
  • Android Image View Pinch Zooming
  • How to concatenate cell values until it finds a…
  • NameError: global name 'xrange' is not defined in Python 3
  • .Net Core 3.1 Entity Framework Slow Query Problem
  • Create IGrouping within IGrouping
  • DirectX and DirectXTK translation limits
  • What does the Excel range.Rows property really do?
  • WAVE file unexpected behaviour
  • Python nonlocal statement
  • VBA code to consolidate data in one row from three rows
  • How to create a fix size list in python?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How can I prevent the TypeError: list indices must…
  • 'int' object has no attribute '__getitem__'
  • What is your most productive shortcut with Vim?
  • Reference - What does this regex mean?
  • What are the undocumented features and limitations…
  • How to prevent scrolling the whole page?
  • Dynamically update values of a chartjs chart
  • Relative imports for the billionth time
  • Efficient way of transforming a ddiMatrix to Bigmatrix in R
  • What does Ruby have that Python doesn't, and vice versa?
  • Python Inverse of a Matrix
  • Getting scroll bar width using JavaScript
  • Set the maximum character length of a UITextField
  • How do I get elements into a nested vector with an…
  • Pandas Merging 101
  • Python Loop: List Index Out of Range
  • How can I get the browser's scrollbar sizes?
  • Single Line Nested For Loops
  • Backbone Collection.fetch gives me Uncaught…
  • PHP parse/syntax errors; and how to solve them
  • Why does this core dumped error happen in my class?…
  • backbone: initialize model subclasses with…
  • Memcached vs. Redis?
  • How to loop through a column to copy all matching…
  • When are static variables initialized?
  • Fastest way to list all primes below N
  • How to change the range slider addition by click on…
  • What is the difference between "INNER JOIN" and…
  • "Notice: Undefined variable", "Notice: Undefined…
  • Does JavaScript have a method like "range()" to…
  • Relationships with Ember CLI Mirage
  • Ukkonen's suffix tree algorithm in plain English
  • How to bind repeating nested templates to complex models
  • Java Multidimensional array - how to create…
  • How to find the continuous sum of the indexed array
  • Are dictionaries ordered in Python 3.6+?
  • Swift Combine, how to cancel the execution
  • Polymer custom element with template-as-content
  • pinpointing "conditional jump or move depends on…
  • List comprehension vs. lambda + filter
  • ValueError: invalid literal for int () with base 10

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Echo newline in Bash prints literal n

Next Post:

How do I remove a property from a JavaScript object?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error