Hello everyone. Welcome to Blog #4, Python: Arrays. This post will introduce you the arrays in Python.
An array is a data structure that can hold multiple data values. An array can be used to keep track of information and store data.
To create an array, first you need to name it, like you would a variable. Arrays are similar to variables, but instead of storing one value that can be changed, it stores multiple values, all of which can be changed. Here is an example:
cars = []
Here, I am creating an array called cars. To create an array, you do, the name of the array, followed by an equal sign, and finally, opening and closing square brackets. At the moment, there is not data being stored in this cars array. You can tell, because there is nothing between the square brackets. Now, I will add, "Honda," and "Nissan," to the cars array:
cars = ["Honda","Nissan"]
Now, the cars array has two things stored in it, 'Honda,' and 'Nissan.'
You have seen how to define an array, but how do you add items to the array without having to re-define the whole thing? You use the append() function. The append() function allows you to add an element to the end of the array. Here is how you call the append function:
cars.append(**the element you want to add to the array**)
As you can see, we are calling the append function on the cars array. We input whatever we want to add between the parentheses that come after the word 'append.' Say you want to add 'Ferrari' to the end of the cars array:
cars.append("Ferrari")
This will take the cars array, and 'append' Ferrari to the end of it.
So now we have covered arrays and how to add elements to them. Finally, how do you address particular elements of the array? You need to know the index of the element. The index of an element is the position at which it is located in the array. The Python programming language uses a zero index, meaning the first element in the array is array[0], and the second is array[1].
Our cars array now looks like this:
["Honda","Nissan","Ferrari"]
Say we want to change "Honda" to "Toyota." To do this, we would need to first figure out where in the array, "Honda," is located. "Honda" is the first element in the cars array, so it is cars[0]. Here is how we change it to "Toyota."
cars[0] = "Toyota"
This takes the 0 index element of cars, which is the first element, "Honda," and changes it to "Toyota." To address a particular index, as you can see, we out the array's name, followed by square brackets containing the index. If the provided index is out of range, meaning that there are not that many elements in the array then the output will be a "List index out of range" error.
Thank you for reading Python: Arrays. Please look out for further posts, and leave comments, questions and suggestions in the comments section!
I learnt a lot about about Lists/Arrays!
ReplyDelete