Section 3.1 Accessing Array Elements
|Learning Objective: |
You might be thinking this is great. Now we can eliminate having to write lots of variables to store data, but a good question might be how would we access this data. We will introduce you to indices and elements. Elements are the slots we have allocated that hold a specific value in the array. An index is an integer that denotes a position in the array. Like in most programming languages and in this book we will use zero-based indexing.
|check-point zero-based indexing means we start counting the index from 0 rather than one.|
|So the first element will be at position 0, Python is zero-based.|
|However, not all programming languages are zero-based indexed.|
Array elements must all be of the same type. So, one element in an array can not be an integer while another is a string. Here is an example.
|String fruits = [“orange”,”apple”,”grape”,”banana”,”watermelon”]|
|0 1 2 3 4|
In Python, you do not have to explicitly state the number of slots, therefore is this how you will achieve the same thing.
Fruits = [“orange”,”apple”,”grape”,”banana”,”watermelon”]
The elements are the values contained in each slot in the array and the index are the positions starting from 0. So for example in the array above the second position which is at index 1 holds a string value of “apple”
Display fruits ---- output
And if you want to assign a value to a specific index you can do so by specifying which position you would like to modify
Fruits = pineapple
Display fruits ---------output
As you have noticed the last index is always one less than the array size so you have to be careful of off-by-one errors. Trying to access unallocated locations will cause unexpected behaviors. For example fruits may crash the program or output garbage data. Remember to never access slots you have not allocated.
There are other types of data containers that hold a lot of data and allow you to change the information within them easily, such as Lists, Maps(trees), and Stacks. (insert examples) In fact, you can even create your own data container and allow it to hold strings and integers together. This type of programming is called object-oriented programming. The workings of them are beyond the scope of this book, so the only large data container we will use in this book is an array. Below are practical examples for you.
Activity 3.1.1. Activity Coding Exercise.
Save and Run the below program.