Jump to content

Array Initialization: Difference between revisions

→‎Python: Put example in Arrays
(→‎Modula-3: Covered)
(→‎Python: Put example in Arrays)
Line 181:
Prelude Data.Array> newArr (0,0) (5,5) 0
array ((0,0),(5,5)) [((0,0),0),((0,1),0),((0,2),0),((0,3),0),((0,4),0),((0,5),0),((1,0),0),((1,1),0),((1,2),0),((1,3),0),((1,4),0),((1,5),0),((2,0),0),((2,1),0),((2,2),0),((2,3),0),((2,4),0),((2,5),0),((3,0),0),((3,1),0),((3,2),0),((3,3),0),((3,4),0),((3,5),0),((4,0),0),((4,1),0),((4,2),0),((4,3),0),((4,4),0),((4,5),0),((5,0),0),((5,1),0),((5,2),0),((5,3),0),((5,4),0),((5,5),0)]
</lang>
 
==[[Python]]==
 
Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:
 
<lang python>
myArray = [0] * size
</lang>
 
However this will not work as intended if one tries to generalize from the syntax:
 
<lang python>
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
</lang>
 
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of mutables (strings, numbers) and immutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.
 
To initialize a list of lists one could use a pair of nested list comprehensions like so:
 
<lang python>
myArray = [[0 for x in range(width)] for y in range(height)]
</lang>
 
That is equivalent to:
 
<lang python>
myArray = list()
for x in range(height):
myArray.append([0] * width)
</lang>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.