Arrays (lists, if you ask Python)

An array is an ordered collection of values. Each item in an array is called an element. In Python, there can be an indefinite number of elements in an array. Python has a special name for its implementation of arrays, called a list. With regard to Python, I will use both words to refer to the same thing.

The following syntax can be used to create an array:

<arrayName>=[<element1>,<element2>,<element3>,...]

Inside square brackets, each element in the array is listed, separated by commas:

>> myArray = ["foo","bar","sup?","yo!"]
>> print(myArray)

The elements of an array can be accessed by their relative position, or index, in the array. To access an element of an array, you can use the following syntax:

>> <arrayName>[<index>]

For example:

>> print(myArray[0])
>> thirdElement = myArray[2]
>> print(thirdElement)

You may have noticed that the index of the third element of the array is 2, and not 3. This is because indexing starts with zero in Python and many other languages. This can be a bit confusing when starting out. When indexing arrays, be sure to access the nth element of an array using the number, n-1. Also notice that the index of the array has an integer data type. If you try to access an array with a float value, it will cause an error even if it represents an integer number (that is, 1.0).

You can also set the value of a particular element of an array by assigning a value to its index. The following line will set the first element of myArray to the string, I'm a new value:

>> myArray[0] = "I'm a new value"
>> print myArray[0]

You can only access or set a value of an array if the index belongs to the array. The following two lines will generate an error, because the array only has four elements, so its maximum index is three (for the fourth element):

>> myArray[6]
>> myArray[4]

Arrays are useful to represent grouped collections of data like a row in a spreadsheet. By keeping track of a set of data items in an ordered list, it is possible to easily store and retrieve items from a grouped collection of data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset