03/07/2024

Week 3 Learning Summary

 Week 3 subject 1: Tuples

  • Tuples are just like Lists, only they're immutable, i.e., their elements, and the numbers of elements, can't be altered.  HOWEVER, the elements are immutable doesn't mean that the elements of the elements can't be altered.  
    • Example, if an element of a Tuple is a List, you can't replace the List with another, but you can alter the elements of the List.
  • There are limited operations applicable to Tuples, including the len() function, and the .count() and .index() methods.

Week 3 subject 2: Dictionaries

  • Dictionarys are like Lists, but their elements are pairs: Key:ValueKeys are just like subscripts of Lists only that they can be of many other data types and other values.
  • Dictionary is perfect for registers, dictionaries and anything you need to use an index to locate values.
  • Use methods like .items(), .keys() and .values().items() returns a list of Tuples, while other two return Lists.
  • You can't use arithmetic operations like + or * with a Dictionary.
  • Learn how to tell if one Key exists in a Dictionary?  What about one Value?
  • There's no .append().  Use assignments directly.  
    • Note the difference with Lists where you can't assign value to an element that hasn't been appended yet.
  •  A Dictionary can be initialised 
    • Using initialisers directly like d = {1:'one', 2:'two', 3:'three},
    • Using the dict() constructor like d = dict([(1, 'one'), (2, 'two'), (3, 'three)]), note the parameter of dict() is a list of tuples,
    • There's a fancier while more confusing way, when Keys are simple strings: d = dict(one=1, two=2, three=3)
    • Using the .fromkeys() method like d = dict.fromkeys([1,2,3], "numbers")
  • As I said, keep exploring all the possibilities!

Week 3 subject 3: File Operations

  • File means text files.  It's a giant leap forward which means you are finally free from keystrokes and can now process something much more complex and more meaningful!
  • Always use the open() function to open a file before using, which returns a File object you'll need to refer to whenever you need to operate a file.
  • Always use the .close() method to close the file after use.
  • Read from files using:
    • .read(number of characters)
    • .readline()
  • Pay attention lines read from a File contain the newline characters at the end of each line.
  • You can use File like a list of lines with for l in f: 
  • ATTENTION: the File object keeps track of the current position read.  It always moves forward.

No comments: