Anonymous user
Array Initialization: Difference between revisions
no edit summary
(Added C++ example) |
No edit summary |
||
Line 60:
++it)
*it = ++val;
== {{header|Python}} ==
Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:
<python>
myArray = [0] * size
</python>
However this will not work as intended if one tries to generalize from the syntax:
<python>
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
</python>
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:
<python>
myArray = [[0 for x in range(width)] for y in range(height)]
</python>
That is equivalent to:
<python>
myArray = list()
for x in range(height):
myArray.append([0] * width)
</python>
|