官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 桃源县| 昌都县| 南昌市| 临江市| 温州市| 高唐县| 五家渠市| 涡阳县| 甘孜县| 丽水市| 五指山市| 长治市| 柳林县| 东港市| 托克托县| 元朗区| 孟连| 闵行区| 务川| 伊金霍洛旗| 栖霞市| 溧水县| 安平县| 富平县| 黄大仙区| 西昌市| 南汇区| 鄢陵县| 沙雅县| 鄂尔多斯市| 嘉义县| 星子县| 泽普县| 海城市| 湖州市| 哈密市| 平罗县| 济阳县| 济宁市| 鲜城| 大方县|