Introduction to Python Programming for Business and Social Science Applications. Frederick Kaefer

Чтение книги онлайн.

Читать онлайн книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer страница 22

Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer

Скачать книгу

Because tuples are immutable, they are not useful in all situations. However, there are many reasons to use tuples. In business, there may be values that don’t change (or change rarely, for example, annually). Let’s consider the sales tax rate for several states in a region. As of 2019, the sales tax rates for Chicago, New York, and Los Angeles are 10.25, 8.875, and 9.5, respectively. We could store this in a tuple like so:

      sales_tax = (10.25, 8.875, 9.5)

      Just like lists, we can access individual elements by index (sales_tax[0], etc.). However unlike lists, calling .append, .sort, or .remove will result in errors. This prevents modification to the tuple later in the program. So in this business example, we can avoid the risk of accidentally changing the sales tax rates in this variable, which makes sense as these rates change infrequently. Likewise, for survey respondents, we could store a tuple of respondent_ID values that could be linked to an individual survey. This can ensure that we have an unchanging set of respondents to study, and using a Python tuple can allow the programmer to maintain a set that will not be modified in any way throughout code that performs analyses.

      Tuples are also sequences, and so we can use all the sequence operations just discussed with tuple objects. We can create a tuple object in several ways. We create an empty tuple object by using an assignment statement in which the right-hand side has an empty parenthesis (as opposed to using square brackets for creating a list object). We can create a tuple with only one element by using an assignment in which the right-hand side has a value and a trailing comma. We can include the element and trailing comma in parentheses, but the parentheses are optional, as it is the presence of the comma that indicates the creation of a tuple (Python Software Foundation, 2019, “Tuples”). We can create a tuple with multiple elements by having multiple elements separated by commas on the right-hand side of the assignment statement (optionally enclosed in parentheses).

      The Python code in Figure 3.13 is almost identical to the code in Figure 3.1, with the difference being that we are creating a tuple in Figure 3.13 and we created a list in Figure 3.1. The tuple object created on line 3 of Figure 3.13 comprises four objects, the first being a string, the second an integer, the third a float, and the fourth a Boolean-type object. As in a list, each of the objects that are in a tuple can have different data types, and when working with tuples, each element is referenceable using an index value. We reference the first item in the list using the index value 0, the second item using index value 1, and so on. We illustrate this mechanism for referencing items in a tuple in lines 8, 10, 12, and 14 in Figure 3.13.

      A screenshot displays a Python code in a Python file for assigning tuples. Description

      Figure 3.13 Assigning Tuples

      We show the output from executing the Python code in Figure 3.13 in Figure 3.14. The only difference between this output and the output from executing the Python code in Figure 3.1 is that the data type for the taxi_ride_info variable is now a tuple. It is important to note that we cannot use the same .append(), .insert(), .pop(), or .remove() methods that we used with a list on a tuple because a tuple is immutable. However, as we have just seen, we can examine and assign indexed elements of a tuple just as we were able to do with a string, which is another immutable sequence object.

      A screenshot displays the output of the Python code for assigning tuples.Description

      Figure 3.14 Output from Assigning Tuples

      Figure 3.15 illustrates the creation and use of a tuple using data related to the GSS data set that we will be working with throughout the textbook. We introduce and describe this data set in Chapter 1 (see Tables 1.4 and 1.5). Line 2 of the code in Figure 3.15 creates a tuple containing ages of a selection of survey respondents. Lines 4 through 6 use some common sequence operations on the tuple to report how many respondents were in the tuple, how old the oldest respondent was among the respondents, and how old the youngest respondent was among the respondents.

      A screenshot displays a Python code illustrating the GSS Tuples example.Description

      Figure 3.15 GSS Tuples Example

      The output from executing the code in Figure 3.15 is in Figure 3.16. This output illustrates that there were seven respondents, the oldest was 59 years old, and the youngest was 19 years old. We could have seen this ourselves from the values assigned to the respondent_ages tuple object, but from a much larger number of respondents, this would been much more difficult to discern visually and just as easy for the Python code to determine and report to us.

      A screenshot displays the output from the execution of the Python code for the GSS Tuples example.Description

      Figure 3.16 Output from GSS Tuples Example

       Stop, Code, and Understand!

      SCU 3.5 Tuple Operations

      Download the file “SCU 3_5.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 Python code where indicated to print out the number of times the value 3 is in the tuple. Execute the modified program after the change to verify that the revised code runs and produces the correct result.

A screenshot displays two lines of code in Python IDLE editor as follows. Line 1: tuple_variable = (3, 5, 7, 3, 2, 5, 2, 7, 3, 3). Line 2: # Add a line of code to print out how many times the value 3 is in the tuple.

      Lessons learned: In this section, we learned about tuples, which are immutable sequences. Tuples have important usages when we have sequences of elements that we do not want to change.

      Dictionaries

      Another very useful data type to learn is the dictionary. A dictionary (commonly referred to as a dict) is a mapping that stores data in key-value pairs, rather than simply a list or sequence of values. A mapping is a collection that allows you to look up information associated with key values (Zelle, 2010). Dictionary keys locate values within a dictionary and can be any immutable type, most often being strings or numbers. However, you should not use floating point numbers as dictionary keys because computers store them as approximations (Python Software Foundation, 2019, “Mapping Types—dict”). Known in other languages as associative arrays or hash tables, this enables the programmer to store multiple related data values in one structure and reference them by their specified key values. Consider a physical dictionary. The “key” is the word you would like to reference, and the “value” would be the definition for which you are searching. Understanding how dictionaries work will help you when we work with data from the Web using JavaScript Object Notation (JSON; in Chapter 7) and when we transform data into required formats for data visualization (in Chapter 9).

      One way to create a dictionary object is to use an assignment statement in which the right-hand side has key-value

Скачать книгу