Jump to content

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 (array[0])</syntaxhighlight>
 
A simple, single-dimensional array can also be initialized thus:
 
<syntaxhighlight lang="python">myArraymy_array = [0] * size</syntaxhighlight>
 
However, this will not work as intended if one tries to generalize from the syntax:
 
<syntaxhighlight lang="python">myArraymy_array = [[0] * width] * height # DOES NOT WORK AS INTENDED!!!</syntaxhighlight>
 
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 differingdifferent semantics of immutables (strings, numbers) and mutables (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:
 
<syntaxhighlight lang="python">myArraymy_array = [[0 for x in range(width)] for y in range(height)]</syntaxhighlight>
 
That is equivalent to:
 
<syntaxhighlight lang="python">myArraymy_array = list()
for x in range(height):
myArraymy_array.append([0] * width)</syntaxhighlight>
 
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 (array[len(array)])
except IndexError as e:
# Print the exception.
print (e)
</syntaxhighlight>
 
6

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.