FTB 05 – Iterating Through Arrays

Previous: Arrays and Matrices

Arrays are versatile – one of the greatest things about arrays is the ability to iterate through an array, so here is an example.

anArray = [1.5, 3.5, 7.2, 9.5]
for anElement in anArray:
    print(anElement)

""" Output
1.5
3.5
7.2
9.5

This is a relatively easy way to iterate through the array – in this case the for/in sequence simply assigns each successive value in the array to the variable anElement and the example simply prints them. Here is another method that is more complex with a full analysis of the code – the output is exactly the same as above.

anArray = [1.5, 3.5, 7.2, 9.5]
for anIndex in range(0,len(anArray)):
    print(anArray[anIndex])

Line 1 – simply declares the array with its 4 elements
Line 2 – creates a variable anIndex that takes the values successively from 0 to len(anArray). The function len(anArray) returns the length of the array (which is 4). The for loop does not execute the last element in the range.
Line 3 – Prints the element of the anArray at index anIndex

So the output is the same as the first example. Here is another way of doing exactly the same thing;

anArray = [1.5, 3.5, 7.2, 9.5]
anIndex = 0
while anIndex < len(anArray):
    print(anArray[anIndex])
    anIndex += 1

This example is similar to the while loop that we did previously. In this example we must specifically increment the index anIndex which is done in the final line of the while loop using the += operator which simply adds 1 to the current value of anIndex.

Here is a method called list comprehension which provides us a nice little shortcut in code to execute a simple print of the list. Note that print is simply a function that prints the output – so this can be replaced with any function that uses an element of the array as an argument. As with all the others methods, the printed output will be the same.

anArray = [1.5, 3.5, 7.2, 9.5]
[print(anElement) for anElement in anArray]

By now you should be able to get a good feel of what an array (also called a list) is in Python. Lets go to the next level and start looking at arrays of arrays – or as we know them; matrices.

Resources

Next: Matrices in Python