Lists Exercises

Do the following exercises in pythontutor.com:

Lists Introduction

  1. Create a list with your favorite lunches
  2. Calculate and display the number of elements in your list
  3. Display just your very most favorite lunch
  4. Create an empty list named lunchesToTry

List Membership

  1. Test if "rice and beans" is in your favorites list (using the list membership operator)

List Concatenation

  1. Add one or more lunches to your favorite lunch list (using the list concatenation operator)

List Slicing

  1. Display three or more lunches using list slicing

List Deletion

  1. Remove your least favorite lunch from the list and then display the list

Objects and References

  1. Explain what each of the following do:
    1. ==
    2. id()
    3. is
  2. Given the following Python code:
    crazyList1 = [1, True, [ 'sublist', 42], 'A' ]
    crazyList2 = [2, False, [ 'sublist', 42], 'B' ]
    Draw how crazyList1 and crazyList2 are stored in memory
  3. Before executing the following Python code, determine what the output will be:
    crazyList1 = [1, True, ['sublist', 42], 'A' ]
    crazyList2 = [2, False, ['sublist', 42], 'B' ]
    
    print( crazyList1[0] )
    print( crazyList1[2] )
    print( id( crazyList1 ) )
    
    print( crazyList1 is crazyList2 )
    print( crazyList1 == crazyList2 )
    
    print( crazyList1[2] is crazyList2[2] )
    print( crazyList1[2] == crazyList2[2] )
    
    crazyList3 = crazyList1
    
    print( id( crazyList3 ) )
    
    print( crazyList1 is crazyList3 )
    print( crazyList1 == crazyList3 )
    
    crazyList4 = list( crazyList1 )
    
    print( id( crazyList4 ) )
    
    print( crazyList1 is crazyList4 )
    print( crazyList1 == crazyList4 )
    

Aliases and Cloning Lists

  1. What is a synonym for a Python alias?
  2. What is a synonym for cloning in Python?
  3. What is the major difference between aliases and cloning?
  4. How do we make an alias for a list in Python?
  5. Name 2 ways to clone a list:
  6. Write some Python code that uses your favorite lunches list that exemplifies the differences between aliases and cloning. Write in the comments where you are making an alias and where you are cloning.

Repetition Operator and Lists

  1. Explain what each of the following do:
    1. ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] * 52
    2. [ ] * 52
  2. What is the scenario that you need to be cautious about with repetition and lists (and why)?

List Methods

  1. Describe to your neighbor what the following list methods do:
    nums = []
    nums.append( 42 )
    nums.extend( 1 )
    nums.extend( [5, 7, 9, 1] )
    nums.insert( 2, 3 )
    nums.remove( 7 )
    print( nums.pop() )
    print( nums.pop( 1 ) )
    nums.sort()
    nums.reverse()
    print( nums.index( 3 ) )
    print( nums.count( 42 ) )
    
  2. The following scripts are the same, except the indentation of counts.append( numExclamations ). What effect does the indentitation have in each of the following:
    1. def exclamationCount( listOfStrings ):
          counts = [ ]
          for string in listOfStrings:
              numExclamations = 0
              for ch in string:
                  if ch == '!':
          	        numExclamations += 1
                      counts.append( numExclamations )
          return counts
    2. def exclamationCount( listOfStrings ):
          counts = [ ]
          for string in listOfStrings:
              numExclamations = 0
              for ch in string:
                  if ch == '!':
          	        numExclamations += 1
                  counts.append( numExclamations )
          return counts
    3. def exclamationCount( listOfStrings ):
          counts = [ ]
          for string in listOfStrings:
              numExclamations = 0
              for ch in string:
                  if ch == '!':
          	        numExclamations += 1
              counts.append( numExclamations )
          return counts
    4. def exclamationCount( listOfStrings ):
          counts = [ ]
          for string in listOfStrings:
              numExclamations = 0
              for ch in string:
                  if ch == '!':
          	        numExclamations += 1
          counts.append( numExclamations )
          return counts
  3. Which one of the above scripts returns a list, in which each element is the count of "!"s for the corresponding str in listOfStrings?

Built-in Functions for Lists

  1. Write Python code that displays the average rainfall for a month using the following values:
    rainfall = [0.09, 0, 0, 0, 0, 0.81, 0, 0, 0, 0, 1.19, 0.08, 0, 0, 0, 0, 0, 0.22, 0.08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.77, 0.05, 0]  # inches
    How short can you make the code (using built-in list functions)?

Iterating Through A List

  1. Given assignments, which is a list, write Python code to do the following:
    assignments = [88, 94, 81, 92, 80, 82, 84, 74, 83, 93]
    1. Display the lowest grade. Write the code in a way that if more values are added to assignments that your code will still work correctly.
    2. Now, extend your script to calculate the average grade, without the lowest grade.
  2. Given grades, calculate how much is needed to shift the highest grade to a 100.0. Shift all of the grades by this amount
    grades = [81.9, 76.8, 77.4, 99.4, 66.2, 67.7, 69.7, 85.7, 92, 69.3, 71.3, 73.9]
    
  3. Write Python code that simulates 1,000,000 rolls of two six-sided dice. Display the number of occurrences for each possible value.
    Example:
     2 was rolled     28025 times
     3 was rolled     55530 times
     4 was rolled     83003 times
     5 was rolled    111318 times
     6 was rolled    138968 times
     7 was rolled    166302 times
     8 was rolled    138591 times
     9 was rolled    111151 times
    10 was rolled     83449 times
    11 was rolled     55804 times
    12 was rolled     27859 times
    Click HERE for a hint.
  4. Write a Python script that does the following:
    • Prompt the user to enter a word.
    • Store each letter as a separate element in a list.
    • Display the word (without "[", "]" nor "'"s)
    • Prompt the user for a letter. Display all of the indices that match that letter.

Multidimensional Lists

  1. What does the following code do:
    import random
    
    def main():
    
        #               Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
        daysPerMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        rainfall = []
        month = 0
        for days in daysPerMonth:
            rainfall.append( [] )
            for i in range( days ):
                rainfall[month].append( round(random.random() * 3.0, 1) )
            month += 1
    
        print('rainfall = [')
        for month in rainfall:
            print( '  ' + str(month) + ',' )
        print(']')
    
    if __name__ == '__main__':
        main()
    
  2. Extend the code above to calculate the average per month and the overall average