DOC PREVIEW
MIT 6 189 - Immutable Objects

This preview shows page 1-2 out of 5 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Page 1 6.189 – Notes Session 8 Day 6: Immutable Objects Earlier, we made a big deal about the fact that lists are mutable. The reason this is important is because certain objects are immutable – once created, their value cannot be changed. Strings are a prime example of this. Although we treated strings the same as primitives like integers and booleans earlier, strings are actually objects. Why did we do this? Think about this: if an object is immutable, it doesn't matter whether two variables are pointing to the same string or two different strings with the same value! Thus, while strings are actually immutable objects, we can treat them as we have before – as primitives. The only new meaning this revelation has is that like lists, strings have member functions. For strings (and tuples, when we get to them), its easiest to think of them like primitives – directly stored in the variable table. Day 6: Strings Revisited Most of the member functions in lists modified the list and had no return value. Strings are immutable, though – how do string member functions work? It turns out that member functions of strings tend to return a new string. Program Text: message = "Hello" print message message.lower() #no effect print message message = message.lower() print message Output: Hello Hello hello Note: lower() is a function that converts a string into lowercase. Here is a list of some useful string functions. Don't try to memorize these! Even I don't remember them – instead, when I need to look up a function I go to the Python Quick Reference website shown in class (and on the website.)Page 2 A quick reminder before starting: remember that "A" and "a" are completely different characters! When writing functions that manipulate strings, its generally a good idea to deal with a single case (usually lowercase). Functions that return a new string - str.capitalize() / str.lower(). Returns a copy of str with all letters converted to uppercase / lowercase. - str.strip(). Returns a copy of str with all whitespace (spaces/tabs/newlines) from the beginning and end of the string removed. Example: " test ".strip() == "test". - str.replace(old,new). Returns a copy of str with all instances of old within the string replaced with new. Example: "hallo all!".replace("al", "el") == "hello ell!". Functions which return information about a string - str.count(substring). Returns the number of times substring appears within str. - str.find(substring) / str.rfind(substring). Returns the position of the first instance of substring within str. rfind returns the position of the last instance of substring. - s.startswith(substring) / str.endswith(substring). Returns True if the string starts with / ends with substring. Example: "Hello".startswith(“he”) == False, but “Hello”.endswith(“lo”) == True Functions which transform the string into other types - str.split(separator). Returns a list of words in str, using separator as the delimiter string. Example: "hello world, Mihir here".split(" ") returns ["hello","world,","Mihir","here"]. Example: "mississippi".split("s") returns ["mi", "", "i", "", "ippi"]. - separator.join(seq). This one is tricky. It takes a list of strings seq and combines them into a string. Each element in seq is separated by separator in the returned string. Example: " ".join(["hello","world"]) == "hello world" Day 4: Tuples Tuples are the immutable counterpart of lists. Unlike a list, tuples cannot be changed. Why/where are tuples useful? Think of a tuple as multi-dimensional data -- just like you can store an integer 5 in a variable, you can also store a two-dimensional coordinate (6,-3). You'll develop an instinct for when to use tuples versus lists as you continue in course 6 – just remember that it tends to be much easier to use tuples whenever you can get away with it. You can create tuples by using parentheses: (1,3,8) creates the tuple with elements 1, 3, 8. As you should expect, tuples are ordered: (1,3) != (3,1)uple (a tuple with one element), you can use5se three formats usingthatteger), whereas the latter is a tuple that contains three elements.ered in the nextples of sequencese of characters.nythinge syntax.e item (or character) at thelength of a sequence.eqring, e.g.plus operator tosome integerach chpic of this class:. Where lists stored a sequence of items, dictionaries store a table.If you want to create a singletonle(5)(5,) !mer is a tuple and(4,6) != [4,6,convert between thst(x)You can nest tuples in tuples! Notuple that containstwo elements (one tuple and one i ree elements.will be coLists, strings and tuples are all exahe case of strings,you can think of them as a sequenSequence isn't an official term ore are very similar.In fact, they share much of the sawill return treturns theequencex ineck if a substring is in a s. You can use thme type. You cantimes fo. We learned that theany sequencefor strings, it iterates throughAnd so we come to the last major tare an mutableobject that we can use to store dat es store a table.tuthey have completely different types (the foone is a tuple and the other is a list. Similarllthe former is atwo elements (one tuple and one integer), whereas the latter is a tuple that contains tof ordered items. Inon that all three of the[0:3] =is equal tocombine two sequences of the sactually works on. Like lists, dictionarieobject that we can use to store data. Where lists stored a sequence of items, dictionarPage 3 If you want to create a singleton t tuple (a tuple with one element), you can use tup ple(5) or use the notation (5,). Note that (5,) != = 5 – they have completely different types (the for rmer is a tuple and the latter is an integer. Also note that (4,6) != [4,6] ] – one is a tuple and the other is a list. Similarly y, ("a","b") != "ab". You can convert between the ese three formats using str(x), tuple(x), and liist(x), though. You can nest tuples in tuples! Note e that ((1,2),3) != (1,2,3) – the former is a t tuple that contains two elements (one tuple and one in nteger), whereas the latter is a tuple that contains thhree elements. Notation for using tuples will be covvered in the next section. Day ?: Sequence notation Lists, strings and tuples are all exam mples of sequences – a series of ordered items. In t the case of strings, you can think of them as a sequenc ce of characters. Sequence


View Full Document

MIT 6 189 - Immutable Objects

Download Immutable Objects
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Immutable Objects and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Immutable Objects 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?