Create a two-dimensional array at runtime: Difference between revisions

Content added Content deleted
No edit summary
Line 361: Line 361:
{{works with|Python| 2.5}}
{{works with|Python| 2.5}}


<lang python> width = int(raw_input("Width of myarray: "))
<lang python>width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in xrange(height)]
myarray = [[0] * width for i in xrange(height)]
myarray[0][0] = 3.5
myarray[0][0] = 3.5
print myarray[0][0]</lang>
print myarray[0][0]</lang>


'''Note:''' Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator creates ''n'' references to [[0] * width]
'''Note:''' Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator creates ''n'' references to [[0] * width]
Line 371: Line 371:
You can also use a two element tuple to index a dictionary like so:
You can also use a two element tuple to index a dictionary like so:


<lang python> myarray = dict(((w,h), 0) for w in range(width) for h in range(height))
<lang python>myarray = dict(((w,h), 0) for w in range(width) for h in range(height))
# or, in Python 3: myarray = {(w,h): 0 for w in range(width) for h in range(height)}
myarray[(0,0)] = 3.5
print myarray[(0,0)]</lang>
myarray[(0,0)] = 3.5
print myarray[(0,0)]</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==