Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Tuples, Lists and Dictionaries - Python

Chapter: Internet & World Wide Web HOW TO PROGRAM - Python

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Tuples, Lists and Dictionaries - Python

In addition to basic data types that store numerical values and strings, Python defines three data types for storing more complex data: the list—a sequence of related data, the tuple (pronounced too-ple)—a list whose elements may not be modified and a dictionary—a list of values that are accessed through their associated keys.

Tuples, Lists and Dictionaries

 

In addition to basic data types that store numerical values and strings, Python defines three data types for storing more complex data: the list—a sequence of related data, the tuple (pronounced too-ple)—a list whose elements may not be modified and a dictionary—a list of values that are accessed through their associated keys. These data types are high-level implementations of simple data structures that enable Python programmers to manipulate many types of data quickly and easily. Some Python modules (e.g., Cookie and cgi) use these data types to provide simple access to their underlying data structures. Figure 28.7 is a program that illustrates tuples, lists and dictionaries.


 

    # Fig. 28.7: fig28_07.py

    # A program that illustrates tuples, lists and dictionaries.

          # tuples                         

          aTuple = ( 1, "a", 3.0     )           # create tuple

          firstItem = aTuple[ 0     ]                       # first tuple item

          secondItem = aTuple[ 1            ]           # second tuple item

          thirdItem = aTuple[ 2    ]                       # third tuple item

      print "The first item in the tuple is", firstItem

      print "The second item in the tuple is", secondItem

      print "The third item in the tuple is", thirdItem

      print

        firstItem, secondItem, thirdItem = aTuple

      print "The first item in the tuple is", firstItem

      print "The second item in the tuple is", secondItem

      print "The third item in the tuple is", thirdItem

      print

      aTuple += ( 4, )

      print "Used the += statement on the tuple"

      print

      # print the tuple

      print "The raw tuple data is:", aTuple

      print "The items in the tuple are:"

      for item in aTuple:   # print each item

print item,

                       

          print     # end previous line

          print     # blank line

                       

          # lists              

          aList = [ 1, 2, 3 ]         # create list

          aList[ 0 ] = 0    # change first element of list

          aList.append( 5 )       # add item to end of list

                       

          print "The raw list data is:", aList   # print list data

          print                

                       

          aList += [ 4 ]    # add an item to the end of the list

                                   

          print "Added an item to the list using the += statement"

          print

 

          # print each item in the list

          print "The items in the list are:"

         

          for item in aList:

          print item,

           

          print     # end previous line

          print     # blank line

           

          # dictionaries

          aDictionary = { 1 : "January", 2 : "February", 3 : "March",

          4            : "April", 5     : "May", 6 : "June", 7 : "July",

          8            : "August", 9            : "September", 10 : "October",

          11 : "November"       }

          aDictionary[ 12 ] = "December"    # add item to dictionary

                       

          print "The raw dictionary data is:", aDictionary

          print "\nThe entries in the dictionary are:"

 

          for item in aDictionary.keys():

          print "aDictionary[ ", item, " ] = ", aDictionary[ item ]

The first item in the tuple is 1

The second item in the tuple is a

The third item in the tuple is 3.0

 

The first item in the tuple is 1

The second item in the tuple is a

The third item in the tuple is 3.0

 

Used the += statement on the tuple

 

The raw tuple data is: (1, 'a', 3.0, 4) The items in the tuple are:

1 a 3.0 4

 

The raw list data is: [0, 2, 3, 5]

 

Added an item to the list using the += statement

 

The items in the list are: 0 2 3 5 4

 

The raw dictionary data is: {12: 'December', 11: 'November', 10: 'Oc-tober', 9: 'September', 8: 'August', 7: 'July', 6: 'June', 5: 'May', 4: 'April', 3: 'March', 2: 'February', 1: 'January'}

 

The entries in the dictionary are: aDictionary[ 12 ] = December aDictionary[ 11 ] = November aDictionary[ 10 ] = October aDictionary[ 9 ] = September aDictionary[ 8 ] = August aDictionary[ 7 ] = July aDictionary[ 6 ] = June aDictionary[ 5 ] = May aDictionary[ 4 ] = April aDictionary[ 3 ] = March aDictionary[ 2 ] = February aDictionary[ 1 ] = January

 

 

Fig. 28.7 Program illustrating tuples, lists and dictionaries

 

Line 5 creates a tuple, with elements 1, "a" and 3.0. Tuples are created as a comma-separated list of values inside parentheses. A tuple is used most often to contain combina-tions of many data types (e.g., strings, integers, other tuples, etc.). Lines 6–8 use the []operator to access specific elements through an index. The first element in a tuple has index 0.

 

Tuple element contents are immutable—they cannot be modified. So, the statement

 

aTuple[ 0 ] = 0

 

produces a run-time error similar to

          Traceback (innermost last):

          File "<interactive input>", line 1, in ?

          TypeError: object doesn't support item assignment

Attempting to access a value at a non-existent element is also an error. The statement

 

print aTuple[ 10 ]

 

produces a run-time error similar to

 

Traceback (innermost last):

File "<interactive input>", line 1, in ?

IndexError: tuple index out of range

 

because aTuple does not have a 10th element.

Line 15 unpacks the items of the tuple into three variables. This statement produces the same results as lines 6–8. Line 21 has the effect of adding an element to the end of variable aTuple. The right-hand side of the += statement must be a tuple; therefore, we must specify a one-element tuple or singleton on the right side of the statement. The value ( 4, ) is a one-element tuple. The comma after the tuple element value is mandatory, because the value ( 4 ) is an integer.

Because tuples are immutable, the += statement actually creates a new tuple that com-bines the tuple on the left side of the += sign (i.e., aTuple) with the tuple on the right side of the += sign (i.e., ( 4, )) to create a new tuple. The new tuple is stored in variable aTuple.

 

The output of line 26 shows how the print statement handles a variable that is a tuple. Lines 29–30 use a for loop to print each element in variable aTuple.

 

The statement in line 29 assigns the first element in aTuple (i.e., aTuple[ 0 ]) to variable item. Line 30 then prints the value of variable item to the screen. The for loop iterates over each element in the tuple, assigns the element to variable item and executes the code in line 30.

 

By default, the print statement writes a newline character (e.g., a carriage return) at the end of its output; however, the comma in line 30 tells Python not to print the newline char-acter. In the next iteration of the for loop, the print statement writes text to the screen on the same line as the previous print statement. Lines 32–33 print a new line and a blank line to the screen, respectively, after all the elements in the tuple have been displayed

 

Line 36 creates a list that contains elements 1, 2 and 3. Python lists are similar to tuples, except that Python lists are mutable (they may be altered). Line 37 demonstrates this fact by assigning the value 0 to the element in the list at index 0. Line 38 adds an element to the end of a list by calling list method append. Lists also support several other methods (Fig. 28.8).

 


The output from the statement in line 40 shows how the print statement handles a variable that is a list. Line 43 adds the integer 4 to variable aList, using the += statement. The value on the right side of the += statement must be a list (or another sequence, such as a string or tuple). In this case, the list contains one element. The for statement (lines 50– 51) prints each element of the list to the screen.

 

Lines 57–60 create a Python dictionary. Each entry in a dictionary has two parts—a key and a value—and a dictionary consists of a set of zero or more comma-separated key-value pairs. A value in a dictionary is manipulated using that value’s key. The key must be of an immutable data type (e.g., number, string or a tuple that contains only immutable data types); dictionary values may be any data type. Each key-value pair takes the form key : value.

 

Line 61 illustrates how to add a new element to a dictionary by using the [] operator. Because a value must be accessed using its corresponding key, each key in a dictionary must be unique. For example, the statements

 

month = { 11 : "November" } month[ 11 ] = "Nov."

 

create a dictionary and then change the value associated with key 11 from "November" to the abbreviation "Nov.".

 

Lines 66–67 use a for loop to print each key-value pair in variable aDictionary. Method keys returns an unordered list of all keys in the dictionary. Dictionaries also sup-port several other methods (Fig. 28.9). The for loop iterates over each key and prints the key and its corresponding value. Each value in the dictionary is accessed using the [] oper-ator (line 67).




Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.