Introduction to Python Programming for Business and Social Science Applications. Frederick Kaefer. Читать онлайн. Newlib. NEWLIB.NET

Автор: Frederick Kaefer
Издательство: Ingram
Серия:
Жанр произведения: Зарубежная деловая литература
Год издания: 0
isbn: 9781544377452
Скачать книгу
Python IDLE editor and execute the program to see the output, which is a list of five values. Add a Python code statement where indicated to change the entry True to be False. Execute the modified program after the change to verify that the revised code runs and produces the correct result.

      List Methods

      As described in the last chapter, in addition to having values, objects also have methods, which are actions we can perform on or with an object. We frequently use methods of compound data types, but more primitive objects also have useful methods. For example, float objects have a method .is_integer() that will return True if the value of the float object is a whole number and False if the value has a nonzero decimal part. To use a method of an object, we use the dot operator to indicate which specific object and which specific method are involved. To do this, we identify the object by name, then indicate the dot operator “.” and then identify the method by name, following the syntax “object.method().”

      We identify and describe some of the most commonly used list methods in Table 3.1. The .append() method adds a new value to the end of a list, increasing the number of elements that are in the list. Using this method repeatedly, lists can grow to keep track of all kinds of information. The .insert() method also adds a new value to a list, but in a specified position. Note that a list must exist prior to using any of the methods, and so we cannot use the .append() method or the .insert() method to create a list. The .pop() method removes and returns the last value in a list, reducing the number of items in the list by one. The .remove() method also removes an item of a specified value from a list; however, it will end in an error if there are no items in the list that have the specified value. If the value appears more than one time in the list, we only remove the first occurrence.

      Lists enable the programmer to store multiple values in one variable. There are many applications of this, including survey responses. Let’s say we have a list of responses to Question 1 of a survey:

      Q1_responses = [9, 4, 10, 5, 10, 3, 8]

      We can then use the len function on the list (len(Q1_responses)) to see that the length of the list is 7. If we receive a new response, we can use the list .append() method to append a value:

      Q1_responses.append(7)

      If we check the length, we can see that it is now 8. We can also use the .insert() method to insert a value at a given place in the list. The syntax is list.insert(position, value).

      If we want to remove a value, we can use the .remove() method. Note that this will remove the first occurrence of the value we pass. So if we execute Q1_responses.remove(10), we will be left with

      [9, 4, 5, 10, 3, 8, 7]

      One more useful method is the .sort() method. This enables the programmer to sort the list in place (meaning we update the value of the variable with the sorted list). Using the .sort() method on our list results in

      [3, 4, 5, 7, 8, 9, 10]

      We can optionally pass the parameter reverse=True to get the list sorted in the opposite order ([10, 9, 8, 7, 6, 5, 4]). Sometimes, we don’t need to sort our data (for example, as we discuss statistics later in the book, the calculations we are interested in will not change if we sort the data or not). However, sometimes it is best to sort, for example, if we are producing a report or want to see the values listed in ascending order in a graph or chart.

      Figure 3.5 illustrates the usage of list methods in Python code. Line 3 creates an empty list by assigning a set of square brackets to a variable (taxi_ride_info = []). Line 5 uses the list .append() method to add a string item to the list (taxi_ride_info.append(“da7a62fce04”)). Lines 6, 7, and 8 also use the list .append() method to add items of different types to the list. Line 10 uses the list .insert() method to add a Boolean value to the list at the third position (taxi_ride_info.insert(2,True)). Note that the position value specified is 2, which is the third element because the first list element has index 0. Line 13 prints out a message and the values of the list after these five items have been added to the list. Figure 3.6 has the output that results from executing this code, and the first line of output shows that the third element of the list has the value True. Line 16 of the code in Figure 3.5 employs the .remove() method of the list to remove the first value True that appears in the list (taxi_ride_info.remove(True)). Line 19 prints a message and the values of the list. We report the result in Figure 3.6, where the first instance of True no longer is a part of the list. Line 22 uses the .pop() method of a list to remove the last item from the list and assign it to a variable (item_removed = taxi_ride_info.pop()). This action creates the variable item_removed, which is a Boolean variable because the value removed from the list is True, a Boolean value. Line 25 of the code in Figure 3.5 prints out a message, the values of the list, and then another message and the value of the variable resulting from the use of the .pop() method. This output is the last line of output in Figure 3.6, where there are now only three items in the list, and the value that had been the last item in the list is now the value of the variable item_removed. We will make great use of lists as we work with data in the remainder of this textbook. Lists are very useful data structures, particularly because they can store values of different data types.

      A screenshot displays a Python code that uses list methods.Description

      Figure 3.5 Python Code using List Methods

      A screenshot displays the output from the execution of a Python code that uses list methods.Description

      Figure 3.6 Output from Execution of Python Code using List Methods

       Stop, Code, and Understand!

      SCU 3.2 Use a List Method

      Download the file “SCU 3_2.py” from the companion website and save it either on your computer or on a removable storage device. Open the file in the Python IDLE editor and add a line of code to append the value 21 to this list using a list method. Execute the modified program after the change to verify that the revised code runs and produces the correct result.

A screenshot displays three lines of code in Python IDLE editor. Line 1: my_list = [3, 5, 8, 13]. Line 2: # Append a value to the list my_list using a list method: Line 4: print(my_list).

      Lessons learned: In this section, we learned about lists that enable us to store multiple values of different data types in the same variable and that each item in a list can be referenced using an index value. We also learned about list methods, which are actions that can be performed to or with lists. Lists are very useful when working with data sets that are made up of different types of data.

       Python Insight

      Python methods and functions are similar yet have an important distinction. As we saw in Chapter 2, functions are subroutines of code that perform a specific task and can return a value. We also can create our own functions to better organize code and enable code reusability. To use a function in Python code, we specify the function name along with any arguments that it might use. Methods also perform a specific task and can return a value, but the important distinction is that methods are directly associated with an object. To use a method,