FTB – Using Arrays and Matrices

Previous: Conditional Logic

We are getting ready to open up the power of one of the most used data structures in programming; the array. It may take a while to wrap your head around them – but once you do, you will quickly learn how they are one of the most powerful structures in programming.

anArray = ["These", "are", "all", "array", "elements"]
print(len(anArray))

The code here will print the number 5. The variable anArray contains 5 elements, all strings. Worth noting is that the array is 0 indexed and the indexes are important as they allow us to access each of the elements of the array.

anArray = ["These", "are", "all", "array", "elements"]
print(anArray[0])

This code will print the string ‘These‘ which is the array element at index 0. A few things to note about arrays.

  • The first element in a Python array is at index 0
  • You can only access elements in the array from 0 to the maximum element which will be one less than the length of the array
  • You can create an array with no elements and append elements to the array.
  • Arrays in Python can contain elements of different types (use with caution)
meArray = [1, "string"]
print(meArray)

""" will output the following

meArray = [1, "string"]
print(meArray)
[1, 'string']

So why are arrays so awesome? In engineering and science we are always needing to keep track of sequences of numbers (we call this data). An array gives us a really easy way to keep track of this data in an easy construct. Here is a nice little data collection algorithm.

myData = []
userInput = float(input("Enter data, use -1 to exit"))
while (userInput >= 0):
    myData.append(userInput)
    userInput = float(input("Enter data, use -1 to exit"))
    print(myData)

Line 1 declares myData as an empty array
Line 2 uses input() function to get user input, converts this to a number using float(), and assigns the value to the variable userInput (all in one line!)
Line 3 starts a loop that will continue until userInput becomes negative
Line 4 appends the current value of userInput to the array myData
Line 5 does the same thing as line 2
Line 6 simply prints out the array myData

So a simple run of this code would look like this;

Enter data, use -1 to exit454
[565.0]

Enter data, use -1 to exit45
[565.0, 454.0]

Enter data, use -1 to exit457
[565.0, 454.0, 45.0]

Enter data, use -1 to exit45
[565.0, 454.0, 45.0, 457.0]

Enter data, use -1 to exit454
[565.0, 454.0, 45.0, 457.0, 45.0]

Enter data, use -1 to exit

Note that there is no space between the prompt for the input, this the numbers are right after the word exit. When working with users you will want to take this into consideration. These are the basics of arrays – as you will learn you can solve many complex problems with this little structure. Next we will start learning how to iterate through arrays.

Next: Iterating Through Arrays