Arrays: Difference between revisions
m
→{{header|Python}}: Python 2 -> Python 3; PEP 8; grammar
(Added Quite BASIC) |
m (→{{header|Python}}: Python 2 -> Python 3; PEP 8; grammar) |
||
Line 6,741:
array[0] = 2
print
A simple, single-dimensional array can also be initialized thus:
<syntaxhighlight lang="python">
However, this will not work as intended if one tries to generalize from the syntax:
<syntaxhighlight lang="python">
This creates a list of "height" number of references to one list object
To initialize a list of lists one could use a pair of nested list comprehensions like so:
<syntaxhighlight lang="python">
That is equivalent to:
<syntaxhighlight lang="python">
for x in range(height):
To retrieve an element in an array, use any of the following methods:
Line 6,771:
# Use the array like a stack. Note that using the pop() method removes the element.
array.pop() # Pop last item in a list
array.pop(0) # Pop first item in a list
# Using a negative element counts from the end of the list.
item = array[-1] # Retrieve last element in a list.
</syntaxhighlight>
Line 6,781:
try:
# This will cause an exception, which will then be caught.
print
except IndexError as e:
# Print the exception.
print
</syntaxhighlight>
|