Module2 Python
Module2 Python
                      MODULE 2
            Python Data Structures:
        Lists, Tuples and Dictionaries
                            Professor
                          Dept. of E&CE
      K.V.G. College of Engineering, Sullia, D.K-574 327
      Affiliated to Visvesvaraya Technological University
                        Belagavi - 590018
Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries
                                          MODULE 2
                   Python Data Structures: Lists, Tuples and Dictionaries
Learning Outcomes
   After reading this Module, the student will be able to:
   o Gain a solid understanding of Python's core data structures: lists, tuples, and
       dictionaries.
   o Know when and why to use each data structure based on its properties and
       performance characteristics.
   o Create and manipulate lists effectively, understanding how to use various list
       methods and functions.
   o Create and utilise tuples in Python programs and Combine lists, tuples, and
       dictionaries to solve complex programming problems.
   o Write Python programs utilising these data structures to store, access, and
       manipulate data efficiently.
   o Develop algorithms that effectively use Python data structures to solve real-
       world problems.
 Chapter 4: Lists (Textbook 1: Page 80-100): The List Data Type, Working with
   Lists Strings. List-like Types: Strings and Tuples.
 Chapter 5: Dictionaries and Structuring Data ((Textbook 1: Page 106-117):
   The Dictionary Data Type Using Data Structures to Model Real-World Things.
       o The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate
           to 'bat', and so on.
       o For example, type the following expressions into the interactive shell.
 Indexing Error: There are two types of errors that occur when there is incorrect
   syntax in indexing
       1. IndexError: If an index exceeds the number of values in the list value, then
           Python gives IndexError. Example
       2. TypeError:          Indexes can be only integer values, not floats. The following
           example will cause a TypeError error:
 Multiple indexing: Lists can also contain other list values. The values in these lists
   of lists can be accessed using multiple indexes. See the example below
       o The first index dictates which list value to use, and the 2nd indicates the value
           within the list value. Ex, spam[0][1] prints 'bat', the 2nd value in the 1st list.
 Negative Indexes: (July 24-8M)
   Negative indexing means starting from the end. -1 refers to the last item, -2 refers to
   the second last item etc. For example
o    As a shortcut, we can leave out one or both of the indexes on either side of the colon
     in the slice.
o    Leaving out the first index is the same as using 0, or a slice beginning of the list and
     leaving out the second index is a slice to the end of the list.
4.3 List Operations: *** Some of the list operations are as follows
         1. Getting a List’s Length with len( )
         2. Changing Values in a List with Indexes
         3. List Concatenation and List Replication
         4. Removing Values from Lists with del Statements
    2. Changing Values in a List with Indexes: We can use an index of a list to change
       the value at that index. To change the value of a specific item, refer to the index
       number. Example 1:
o Example 2:
4.4 Working with Lists: When you first begin writing programs, it’s tempting to
create many individual variables to store a group of similar values. if I wanted to store
the names of my cats, I might be tempted to write code like this. This is bad way to
write code because it leads to have duplicate code in the program.
o   Instead of using multiple, repetitive variables, we can use a single variable that
    contains a list value.
       o Program:
4.5 Using “ for” Loops with Lists: Python Iterate Over a List via for loop You can
loop through the list items by using a for loop.
   - Example 1: Print all items in the list, one by one:
   -
             Program:         thislist = ["apple", "banana", "cherry"]
                              for x in thislist:
                              print(x)
             Output:   apple
                       banana
                       cherry
       o for loop repeats the code block once for each value in a list or list-like value.
o The code in the loop will access the index (as the variable i), the value at that index
    (as supplies[i]) and range(len(supplies)) will iterate through all the indexes of
    supplies, no matter how many items it contains.
o The following program lets the user type in a pet name and then checks to see
    whether the name is in a list of pets.
   o Instead of left-side program we could use right-side program i.e., with the
       augmented assignment operator += to do the same thing as a shortcut.
   o The Augmented Assignment Operators are listed in the below table:
   o The += operator can also do string and list concatenation, while the *= operator
       can replicate string and list.
   o When there are duplicates of the value in the list, the index of its first
       appearance is returned. Example
   o The insert( ) method can insert a value at any index in the list. Example shown
       below, here chicken is inserted in the index 1.
   o The append( ) and insert( ) methods are list methods and can be called only on
       list values, not other values such as strings or integers. It shows an attribute
       error. Example
       o Attempting to delete a value that does not exist in the list will result in a
           ValueError.
       o If the value appears multiple times in the list, only the first instance of the
           value will be removed.
       o The del statement is good to use when you know the index of the value you
           want to remove from the list.
       o The remove() method is good when you see the value you want to remove
           from the list.
       o We can also pass True for the reverse keyword argument to sort( ) the
           values in reverse order using reverse( ) methods
o There are THREE things you should note about the sort() method.
          First, the sort() method sorts the list in place; don’t try to return value by
          writing code like spam = spam.sort().
Second, we cannot sort lists with both number and string values. Example
   Third, sort() uses “ASCIIbetical order(upper case)” rather than actual alphabetical
   order(lower case) for sorting strings
       o If we need to sort the values in regular alphabetical order, pass str. lower for
           the key keyword argument in the sort ( ) method call.
o The pop() method removes the element at the specified position in the list
            - Ask a yes or no question, shake the ball, and then look through the window
              to see the answer.
           Appearance:
            - It's a sphere-shaped like a pool 8 ball, with a cloudy liquid inside and a
              visible window to display the answer.
           Answer types:
            - The answers can be positive ("It is certain"), negative ("Don't count on it"),
              or neutral ("Ask again later").
       Randomness:
        
       - The answers are generated randomly, usually by a 20-sided die floating in
          the liquid.
 How to Implement Magic 8-ball Game in Python
        We can implement the magic 8-ball game in Python using the randint() function
        with if-else statements. Alternatively, we can also use the choice() function
        defined in the random module in Python to implement the magic 8-ball game. Let
        us discuss the choice() function with the list.
      Using The choice() Function
        Instead of the randint() function, we can use the choice() function defined in the
        random module to implement the magic 8-ball game. The choice() function takes
        a list as its input argument and returns a random element from the list. We will
        put all 20 answers in a list to implement the game. After this, whenever the user
        asks a question, we will select a value from the list using the choice function and
        print it as shown in the following example.
import random
while True:
Output:
Conclusion:
In above example, we have stored all the possible answers in a list. When the
user asks for an answer, we directly select a random answer from the list
using the choice() function and print it.
Output
   o Data types in Python are categorized into mutable and immutable data types.
   o Mutable data types are those whose values can be changed once it is created.
       Example: List, Dictionaries, and Set.
   o Immutable data types are ones in which the values can’t be changed or altered
       once they are created. Example: String and Tuples.
   o Difference Between Mutable and Immutable Data Type: Mutable vs Immutable
 String:
   o String is immutable data type, whose elements cannot be changed once it is
       created.
   o Trying to reassign a single character in a string results in a TypeError error.
   o The proper way to “mutate” a string is to use slicing and concatenation to build a
       new string by copying from parts of the old string.
   o We used [0:6] and [7:15] to refer to the characters we don’t wish to replace.
   o Notice that the original 'Zophie a cat' string is not modified because strings are
       immutable.
 List (June 2024-4M, July 24-8M)
   o    A list value is a mutable data type: It can have values added, removed, or
       changed.
   o The list value in eggs isn’t being changed here; rather, an entirely new and
       different list value ([4, 5, 6]) is overwriting the old list value ([1, 2, 3]).
                Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced
                                           with a new list value.
   o If we want to modify the original list in eggs to contain [4, 5, 6], you would have
       to delete the items in that and then add items to it.
Figure: The del statement and the append() method modify the same list value in place.
    Tuple Items:
   o Tuple items are ordered, unchangeable, and allow duplicate values.
   o Tuple items are indexed, the first item has index [0], the second item has
       index [1] etc.
   o The main way that tuples are different from lists is that tuples, like strings, are
       immutable. Tuples cannot have their values modified, appended, or removed.
o Example:
     References:
     o In Python, a reference is a name that points to the location of a value in
        memory. References can be variables, attributes, or items.
     o A variable is a name that refers to an object, and a reference is the connection
        between the variable and the value. As variables store strings and integer values.
     o In above example, we assign 42 to the spam variable, and then we copy the value
        in spam and assign it to the variable cheese. When we later change the value in
        spam to 100, this doesn’t affect the value in cheese. This is because spam and
        cheese are different variables that store different values.
     o But lists works differently. When we assign a list to a variable, we are actually
        assigning a list reference to the variable. A reference is a value that points to
        some bit of data, and a list reference is a value that points to a list.
   o When we create the list ❶, we assign a reference to it in the spam variable. But
       the next line copies only the list reference in spam to cheese, not the list value
       itself. This means the values stored in spam and cheese now both refer to the
       same list. There is only one underlying list because the list itself was never
       actually copied.
   o So when we modify the first element of cheese, we are modifying the same list
       that spam refers to. List variables don’t contain lists—they contain references to
       lists.
Figure: spam = [0, 1, 2, 3, 4, 5] stores a reference to a list, not the actual list.
   o The reference in spam is copied to cheese. Only a new reference was created and
       stored in cheese, not a new list.
   o When we alter the list that cheese refers to, the list that spam refers to is also
       changed, because both cheese and spam refer to the same list.
   o Variables will contain references to list values rather than list values themselves.
   o But for strings and integer values, variables will contain the string or integer
       value.
Figure: cheese[1] = 'Hello!' modifies the list that both variables refer to
    o Python uses references whenever variables must store values of mutable data
       types, such as lists or dictionaries. For values of immutable data types such as
       strings, integers, or tuples, Python variables will store the value itself.
 Passing References
OUTPUT
    o When eggs() is called, a return value is not used to assign a new value to spam.
       Even though spam and someParameter contain separate references, they both
       refer to the same list. This is why the append('Hello') method call inside the
       function affects the list even after the function call has returned
        copy()
         o It can be used to make a duplicate copy of a mutable value like a list or
           dictionary, not just a copy of a reference.
         o Creates a shallow copy of an object. A shallow copy is a new compound object
            that contains references to the original object's objects.
        deepcopy()
         o Creates a deep copy of an object. A deep copy is a new compound object that
            contains copies of the original object's objects.
       Consider the following example below                 the spam and cheese variables refer to
        separate lists, which is why only the list in cheese is modified when you assign 42
        at index 1. ➢ The reference ID numbers are no longer the same for both variables
        because the variables refer to independent lists
Figure: cheese = copy.copy(spam) creates a second list that can be modified independently of the first.
o Example:
   o Dictionaries can still use integer values as keys, just like lists use integers for
       indexes, but they do not have to start at 0 and can be any number.
                             Lists                                          Dictionaries
                                                         Dictionaries are an unordered collection of
        List is an ordered collection of items.
                                                         data in a key: value pair form.
        Uses square brackets [ ].                        Uses curly braces { }.
        Ex: fruits = [“apple”, “banana”, “cherry”]       Ex: person = {“name”: “John”, “age”: 30}
        Ordered: Items have a defined order,
                                                Unordered: Items do not have a defined order.
        which will not change.
        Accessed by index, starting from 0.     Values are accessed using keys.
                                                Does not allow duplicate keys. However,
        Allows duplicate items.
                                                values can be duplicated.
                                                Keys can be of any immutable data type (e.g.,
        It can store any data type.             strings, numbers, tuples). Values can be of any
                                                type.
        Built in functions: append(), remove(), Built in functions: keys(), values(), items(),
        pop(), sort(), etc.                     get(), pop(), etc.
                                                Dictionaries can not be sliced.
         Slicing can be done
5.2.2 The keys(), values(), and items() Methods: (July 2024-8M, Jan2024-8M)
   o Three dictionary methods will return list-like values of the dictionary’s keys,
       values, or both keys and values: keys( ), values( ), and items( ).
   o    The values returned by these methods are not true lists: They cannot be
       modified and do not have an append( ) method.
   o for loop iterates over each of the values in the spam dictionary.
o for loop can also iterate over the keys or both keys and values: Example
   o The list(spam. keys()) line takes the dict_keys value returned from keys() and
       passes it to list(), which then returns a list value of ['color', 'age'].
   o Multiple assignment trick in a for loop to assign the key and value to separate
       variable: Example below
   o Because there is no 'eggs' key in the picnicItems dictionary, the default value 0 is
       returned by the get() method.
   o Without using get(), the code would have caused an error message, such as in the
       following example:
   o The first time setdefault() is called, the dictionary in spam changes to {'color':
       'black', 'age': 5, 'name': 'Pooka'}.
   o The method returns the value 'black' because this is now the value set for the key
       'color'.
   o When spam. setdefault('color', 'white') is called next, the value for that key is not
        changed to 'white' because spam already has a key named 'color'.
     o Importing the pprint module gives you access to the pprint() and pformat()
        functions, which can “pretty print” a dictionary’s values.
     o In the below example we see how that data looks before applying the pprint
        module and after applying it.
      A Tic-Tac-Toe Board
       o Tic Tac Toe is a puzzle game for two players, called "X" and "O", who take turns
          marking the spaces in a 3×3 grid. The player who succeeded in placing three
          respective marks in a horizontal, vertical, or diagonal row wins the game.
       o A tic-tac-toe board looks like a large hash symbol (#) with nine slots that can
          each contain an X, an O, or a blank. To represent the board with a dictionary,
          we can assign each slot a string-value key as shown in below figure.
   o The data structure stored in the theBoard variable represents the tic-tactoe
       board in the below Figure 5.3
   o A board where player O has won by placing Os across the top might look like
       this:
o The data structure in theBoard now represents the tic-tac-toe board in Fig 5-5.
   o The player sees only what is printed to the screen, not the contents of variables.
   o The tic-tac-toe program is updated as below.
o When you run this program, printBoard() will print out a blank tic-tac toe board.
o The printBoard() function can handle any tic-tac-toe data structure you pass it.
o Now when you run this program, the new board will be printed to the screen.
   o Now we created a data structure to represent a tic-tac-toe board and wrote code
       in printBoard() to interpret that data structure, we now have a program that
       “models” the tic-tac-toe board.
   o Program: allows the players to enter their moves.
o When you run this program, it will look something like this:
    o Inside the totalBrought() function, the for loop iterates over the keyvalue pairs in
        guests 1.
    o Inside the loop, the string of the guest’s name is assigned to k, and the dictionary
       of picnic items they’re bringing is assigned to v.
    o If the item parameter exists as a key in this dictionary, it’s value (the quantity) is
        added to numBrought 2.
    o If it does not exist as a key, the get() method returns 0 to be added to
       numBrought.
    o The output of this program looks like this:
 JUNE- 2024
 JULY - 2024
 JULY - 2024
 Dec-2023/Jan 2024
 Dec-2023/Jan 2024
 NOV/DEC -2023
 JUNE/JULY -2023
Acknowledgement:
    My sincere thanks to the author Al Sweigart, because the above contents are
prepared      from     his     textbook       “Automate        the    Boring       Stuff      with     Python:
Practical Programming for Total Beginners”
                             Prepared by:
                             Dr. Suresha V
                             Professor & Principal
                             Dept. of Electronics and Communication Engineering.
                             Reach me at: suresha.vee@gmail.com
                             WhatsApp: +91 8310992434