Читать книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer - Страница 76

Index Values

Оглавление

When working with lists, we can reference each element using an index value. The index value for the first item in the list is 0, the second item has index 1, and so on. An index is a reference to a specific element of a data structure such as a list. When using a list in Python, the index is specified using square brackets (“[ ]”). For example, say we have a list: passengers = [“John”, “Jane”, “Joe”]. The list has three elements, with index values of 0, 1, and 2. We can access the first element, “John,” through referencing passengers[0]. If we attempt to use an index reference outside of the existing elements in the list, we will get an error. Using passengers[5] will result in a “IndexError: list index out of range.” Likewise, if we try to use an index value like 0.5, we will get a “TypeError: list indices must be integers, not float.”

We illustrate this mechanism for referencing items in a list in lines 7, 9, 11, and 13 in Figure 3.1.

Description

Figure 3.1 Python Code with List Object

Figure 3.2 shows the output from executing the Python code in the file Fig 3_1 AssigningList.py (which is in Figure 3.1). Note that the first line of output reports the type of the taxi_ride_info variable to be a list, and each of the following lines of output demonstrates that each item in the taxi_ride_info list has different data types.

Description

Figure 3.2 Output from Execution of Python Code in Figure 3.1

As illustrated above, lists in Python can group together multiple values (i.e., are compound data types). Lists are also mutable, meaning that they are an object type for which the values are modifiable. For example, we can change the value of one of the objects in a list while the remaining items in the list stay the same. Figure 3.3 illustrates Python code that changes one item in a list (line 6) and reports the values in the changed list (line 9). Figure 3.4 illustrates the output from the execution of that code example.

Description

Figure 3.3 Python Code to Change Value of a List Object

Description

Figure 3.4 Python Code to Change Value of a List Object

Introduction to Python Programming for Business and Social Science Applications

Подняться наверх