Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Genomic Data Manipulation BIO508 Spring 2013 Python 01 Python Teeth Stone Knives and Bear Skins We've seen several Python instructions so far, and we were pretty wishy-washy about how they actually worked. We have a pretty good sense of the distinction between data (numbers and strings and lists and dictionaries) and instructions (keywords and things like len or range). We saw a bunch of ways to denote data (quoting for strings, brackets for lists and dictionaries, True and False, plain old numbers...) and a bunch of keywords with very specific syntax (if/elif/else and while, for example). But just to keep you on your toes, these keywords are in some sense the exceptions. These are special forms; things which don't really behave like "normal" elements of Python. So we started with the black sheep 1, and today we're going to meet the rest of the family. Standard functions that are built into Python are known as primitives or primitive functions2 or sometimes the standard library; things that are so basic that they're provided by the language itself. Any function is also an instruction (although, as we saw, not all instructions are functions). And they work pretty much the same way as some of the instructions we already saw: Each Python function consists of a name followed by zero or more arguments wrapped in parentheses, e.g. print( ) or len( [1, 2, 3] ) or range( 2, 4 ). Some Python functions target specific objects; we'll discuss what this means later, but I'd like to demonstrate the syntax now so it won't be a complete mystery if we have to use it. Such functions are also referred to as methods, and they take a special extra input argument, the target. o A method consists of a target object, followed by a period ., followed by the method name. o Just like any other function, the method name is followed by zero or more arguments wrapped in parentheses, e.g. hashHsah.get( "ashes" ) or random.random( ). o The object to the left of the period is the target of the method; that is, the object that's "hosting" the work. For example, in hashHsah.get, the thing you're geting3 is hashHsah. o A method is just a special kind of function, and we'll discuss them later in more detail. Any place4 we could use an expression, we can use a function instead. Specific functions might have different restrictions on their arguments. For example, some functions take exactly one argument; some functions take zero or more arguments; some functions take exactly three arguments. Some functions can take any expression as an argument; some functions can only take numbers; some functions have multiple arguments, each with their own restrictions. When we learn new functions, I'll make sure to specify how many and what type of arguments should be given to them 5. Remember, the plural of sheep is sheep! Technically, in Python, a function is a standalone piece of code and a method is a function attached to a particular class, but I'll occasionally use them interchangeably out of (bad) habit. Both "function" and "method" basically mean, "a cohesive piece of code with a particular name written to do a particular task." 3 Verbing weirds language. 4 Well, there are some special cases... and it only works with functions, not keywords! You can't just drop a break in wherever you'd like. 5 And don't worry - if you happen to mess up, Python will often inform you in no uncertain terms that you did something wrong. Computers are extremely unforgiving of bad programs! Python is more forgiving than most, though, so keep your eyes open. 1 2 S01-1 Telephone Operator First of all, a note on the word "operator". An operator is one who operates, a being performing the task of operation, one who excels in ops or opers and operats with great ability. In Python, an operator is just sort of a shorthand function that puts its arguments around itself rather than between parentheses. This is, of course, meant to mimic the behavior of operators in the mathematical sense, plus and minus and times and whatnot. Python has a bunch of these built in, and they'll look exactly like you expect them to: 1 + 2 is a completely valid Python statement using the + operator to add one and two (returning, one expects, three). There are lots of non-mathematical operators in Python, though, too, so the common thread to remember is that an operator is just a shorthand function with its arguments (or argument; some only take one) beside it to the right and/or left, rather than sequestered away in parentheses to the right. Meta Operators . The dot operator isn't really a normal Python operator, but it's worth mentioning here. In fact, I already mentioned it above, and it's nearly impossible to work with Python for very long without running into it. The . operator allows targeted method invocation; in terminology that we'll see more of later, it allows you to run a method on a specific target (usually an object). The dot operator is always written as target.method, with arguments in parentheses optionally appearing after the method name (just like for any normal function). These are all examples (some of which might not make sense yet): strIng.replace( "rang", "rung" ) hashIng.get( "tag" ) aNana.append( "ba" ) strIpe.find( "white" ) Pretty much all of the rest of the operators we'll cover are instructions that do some sort of work. The dot operator isn't so much of an instruction as it is a formatting aid; it lets the Python interpreter (and you!) know which instructions are being run with what data (target and arguments) as input. = A single equals sign is the Python assignment operator. This evaluates whatever's on the right and assigns it to the variable on the left. We saw this guy before, back in some of the keyword examples, and this is why I didn't want to blow my cover back then. I thought it would be good to go over a quick definition of what operators are in the first place. But now that we know... strString = "string" aList = ["one", 2, 30e-1] iIAmOne = iIAmOneToo = iIAmAlsoOne = 1 hashDays["Wednesday"] = 3 hashDays[3] = aSomeList[5] In case you're curious, the "return value" of an assignment is the value that was assigned (i.e. the right hand side), which is why we can chain them together (as per the third example above). This isn't often terribly important, but it's another interesting factoid that can occasionally be used to create nicer code. S01-2 Numerical Operators +, -, *, / These should come as no surprise. Python has the four basic math operators built in - addition, subtraction, multiplication, and division. In fact, they're pretty much the reason that operators are called operators. Not much to say; they make numbers into other numbers. So you can think of them each as functions that evaluate their right and left arguments and then return the sum/difference/product/quotient of those arguments (which had better be numbers). This means that they can be used individually or, of course, in concert, just like in math: iTwentyButDontWriteThis = 5 * 4 + 10 - 30 / 3 iTwentyWriteThisInsteadForClarity = ( 5 * 4 ) + 10 - ( 30 / 3 ) iThirteenAndAThird = ( ( 5 * ( 4 + 10 ) ) - 30 ) / 3 iSawThreeShips = ( 5 + aiNumbers[ iIndex ] ) if \ ( iSmall < iBig ) else hashNumbers["sailing"] +=, -=, *=, /= These funky guys are all just shorthand for a math operator combined with an assignment. In each case, something of the form: iVar += exp is equivalent to: iVar = iVar + exp where iVar is any variable (not necessarily an integer - floats are fair game, too) an exp is anything that evaluates to a number. I don't often find myself using *= or /=, but it's not too uncommon to find yourself writing things like: iCounter = 0 for var in some list: if some test is true: iCounter += 1 Use these to make your code more readable, not less! Friends don't let friends write messy code. ** In one of the major triumphs of modern computational design, Python actually includes an operator for exponentiation. That is to say, in Python, 5 ** 3 means 53, or five to the third, or 5 * 5 * 5, or 125. Again, not much to say about it, except that this is a demonstration of one of Python's nice features. It's just a plain old math operator like everything else. iEightButDontWriteThis = 3 ** iEightWriteThisInsteadPlease = ( 3 iSomeBigNumber = 2 ** 2 ** 2 iThisIsTheSameThingButBetter = 2 ** ( 2 iBecauseThisIsMuchSmaller = ( ( 2 ** 2 2 - 1 ** 2 ) - 1 ** 2 ** ( 2 ** 2 ) ) ) ** 2 ) ** 2 % If you've ever taken modern algebra, you might fear the modulo operator as a bringer of weird proofs by congruency. Fret not; in Python, the modulo operator is a binary operator that takes two integers as inputs and returns their remainder after division. The return value is the remainder after dividing the thing on the right into the thing on the left. Observe: S01-3 10 11 12 13 14 % % % % % 3 4 5 6 7 1 3 2 1 0 In other words, the remainder when dividing ten by three is one. The remainder when dividing 11 by four is three. And these are pronounced "ten modulo three," "eleven modulo four," and so forth. As an exercise for the reader, go ask a number theorist if they can prove anything interesting about sequences of modular statements like that. Logical Operators not The unary not operator reverses the truth value of whatever statement it's applied to. False or None or 0 become True, and anything true becomes False. This applies to either constants or to whole statements (of course): not 100 False not ( 6 - ( 2 * 3 ) ) False not ( 101 < 010 ) True strString = "strung" iTest = ( 0 if ( not strString ) else 1 ) iResult = not ( 1 if iTest else 0 ) print( str(iTest) + ", " + str(iResult) ) → "1, false" and, or These two operators are known as logical and and logical or, respectively6. They're binary operators (they evaluate the statements to their right and their left) that return true if... and returns true if and only if both its left and right arguments are true. or returns true if either its left or its right argument is true. Hence the names! These guys seem simple, but they have one big trick to watch out for. They're lazy little slobs, and they stop evaluating their arguments as soon as possible. This means that if and's first argument is false, it won't evaluate its right argument; it stops immediately and returns false. And if or's first argument is true, it won't evaluate its right argument; it stops immediately and returns true. This isn't a feature you should necessarily rely on - writing code and assuming that some of it won't execute it generally a poor idea - but it's useful to know in cases where something seems to be failing for no reason. But fortunately, these guys make most of their appearances in conditional statements like if/elses, places where there's not normally a lot of evaluation going on anyhow (just testing). So for example... iWillBeTwo = ( 2 if ( False or True ) else 3 ) iWillBeThree = ( 2 if ( False and True ) else 3 ) iWillBeFour = ( False or 2 ) * ( 2 if ( 3 and 4 ) else 5 ) 6 Which always seems to beg the question whether there's an illogical and or illogical or operator. S01-4 ==, !=, <, >, <=, >= I've glommed these all together because they're all essentially equivalent. You've seen < already, and I bet from that, you can guess what all the rest do. In rapid succession, they're called (unsurprisingly) equivalence, difference, less than, greater than, less than or equal to, and greater than or equal to. They're all binary operators that evaluate their arguments and return True or False based on the results. The only potentially mildly surprising thing about them is that they'll also work for string values, indicating whether their operands are in the appropriate lexical7 order (or, in the case of ==/!=, identical or not). You can get yourself into trouble mixing numbers and strings, though8. It makes sense to test whether a number is equal to a string. It doesn't make sense to test whether a number is less than or greater than a string, but in one of its less desirable behaviors, Python will merrily let you try and produce nonsensical results 9. iWillBeTwo = 2 if ( 0 < 1 ) else 3 iWillBeThree = 2 if ( 0 >= 1 ) else 3 iWillBeThree = 2 if ( 0 == 1 ) else 3 iWillBeTwo = 2 if ( 0 != 1 ) else 3 iWillBeTwoToo = 2 if not ( 0 == 1 ) else 3 print( "weis" if ( 1 == 2 ) else "bud" ) print( "bud" if ( "one" == "two" ) else "weis" ) print( "weis" if ( 1 == "one" ) else "er" ) print( "either" if ( 1 < "two" ) else "or" ) → "bud", "weis", "er", undefined (probably "either") String Operators + The plus sign serves double duty in Python 10. Not only does it perform numerical addition, it represents string concatenation in Python. It's a binary operator that works on strings; it evaluates its left and right arguments and returns a new string consisting of the two of them munged together. This is massively useful for all sorts of things: str(1 + 2) + " is three" "3 is three" "Newlines are nice after numbers like " + str(4 + 5) + "\n" "newlines are nice after numbers like 9.\n" "This can " + "be repeated" + " many times " + "to make longer" + " strings." "This can be repeated many times to make longer strings." Notice those strs sneaking in there to convert numbers into strings! Just like Python gets confused mixing numbers and strings with comparison operators, it doesn't like it when you tell it to + a number and a string. Do you mean to numerically add a number to a string (which doesn't make sense), or do you mean to concatenate a number with a string (which also doesn't make sense)? It doesn't know! And when Python doesn't know something, it lets you know. With an error message! Cue evil laughter. Like alphabetical, but with some quirks (e.g. capital and lower case letters are different). I consider this to be a big argument in favor of using our prefix notation. Python isn't too good on data typing, so we try to give our variables intelligent names to help it out a little. 9 Or if you don't try and just do it by accident. I'd actually love a programming language that had different errors for intentionally bad code as opposed to accidental mistakes. 10 And in several other languages, actually. People are used to the idea of a + meaning "put stuff together." 7 8 S01-5 * The string repetition operator is a little funky and underappreciated. This is actually the first operator we've seen that takes two specifically different kinds of arguments; the left argument must be a string, and the right argument must be an integer. If we call the right hand argument n, the return value is n copies of the left hand argument concatenated together. Not much more to be said... "three" * 3 "threethreethree" "x" * ( 5 * 2 ) "xxxxxxxxxx" s = "" for i in range( 4 ): s += "x" * i print( s ) → "xxxxxx" In the last example, notice that += works just the way we'd expect it to for string concatenation. And that we have to initialize the variable str before we use it; I haven't said much about this because I'm hoping to sweep it mostly under the rug, but Python will yell if you're careless about initializing variables correctly. List Operators You may experience a sudden sense of deja vu 11: + The plus sign serves triple duty in Python. Not only does it perform numerical addition and string concatenation, it represents list extension in Python. It's a binary operator that works on lists; it evaluates its left and right arguments and returns a new list consisting of the two of them munged together. This is massively useful for all sorts of things: [1] + [2] [1, 2] [4, 5] + [9] [4, 5, 9] [1, 1] + [] + [2, [3], [[5]]] + [] + [8] [1, 1, 2, [3], [[5]], 8] * The list repetition operator is a little funky and underappreciated. This is actually the second operator we've seen that takes two specifically different kinds of arguments; the left argument must be a list, and the right argument must be an integer. If we call the right hand argument n, the return value is n copies of the left hand argument concatenated together. Not much more to be said... ["three"] * 3 ["three", "three", "three"] ["x"] * ( 5 * 2 ) ["x", "x", "x", "x", "x", "x", "x", "x", "x", "x"] a = [] for i in range( 4 ): a += ["x"] * i print( a ) → ["x", "x", "x", "x", "x", "x"] 11 Haven't we met before? S01-6 In the last example, notice that += works just the way we'd expect it to for list concatenation. Type-Independent Functions Many of Python's built-in functions (and many of the ones you'll write yourself) are tied to particular data types. **, for example, only accepts numerical arguments12. There are a few that will generally work no matter what kinds of arguments you throw at them, however, collected together in this section for your convenience. cmp( x, y ) This is called the comparison function, and it acts very much like the comparison operators you saw above, == and <= and >= and all those. After evaluating its arguments, it returns -1 if the left argument is less than the right, 0 if they're the same, and 1 if the left argument is greater than the right. It applies to either numbers or strings, just like the operators we just saw. This isn't obviously useful now, but watch out for its star appearance later on in this handout! str(n), float(i), int(s) I'm going to sin by omission here, since these functions hide a world of complexity, but we've already seen basically how they work for type conversion. Python is what's known as strictly typed, in that variables of a particular type (numerical or string or list or whatnot) will never13 be converted automatically to another type. If you try to concatenate a string with a number, as we saw above, ladybugs appear. To circumvent this issue, Python allows you to explicitly convert between types. We'll use this primarily in three ways: o Converting numbers to printable strings using str. o Converting integers to floating point values (to allow proper division) using float. o Converting strings into numbers using int or float. You can actually use str in particular for any object in Python, and it'll convert its target into a string. You can slap a str before just about anything and get back some sort of potentially useful string representation of that value. I wonder what happens when you print out a lists str, hmm? str("I'm already a string") "I'm already a string" str(12) "12" str(12.3) "12.3" str("12.3") "12.3" 12 + " won't work" str(12) + " will work" "12 will work" 1 / 2 0 35 / 8 4 float(1) / 2 0.5 float(1 / 2) 0 1 / float(2) 0.5 1.0 / 2.0 0.5 Although "string power" does sound like a rockin' 80s glam band... Fib. Slightly. I dislike Python's typing - it pretends to be very by-the-books, but then things like print will take any old value and turn it into a string... 12 13 S01-7 float("1") / 2 0.5 float("1 / 2") int("1") / float("2") 0.5 int("1") / int("2") 0 str(int("35") / float(8)) + " = 4.375" "4.375 = 4.375" Numeric Functions abs( n ) The abs function accepts a single arguments, any number, and returns its absolute value. Behold: abs( abs( abs( 1.1 abs( 1.1 12 ) -12 ) + 2.2 ) - 2.2 ) 12 12 3.3 1.1 round( d ) The round function accepts a single argument, any number, and returns (irritatingly) the floating point representation of its closest integer. This is almost never what you actually want, and you usually need to immediately convert the return value using int, but at least its heart is in the right place. I feel like Python's round is the equivalent of a beautiful looking chocolate chip cookie that seems great until you bite in and realize the sugar's been replaced with salt. round( 12 ) 12.0 round( -12.0 ) 12.0 round( 1.1. + 2.2 ) 3.0 round( 1.1 - 2.2 ) -1.0 min( a ), max( a ) While technically not numerical functions, min and max are in the same spirit, and I'll include them here to pad out the section a bit (lists have plenty of their own functions to discuss). Both methods take a single list of numbers as input and do the obvious things: max( [1, 3, -2, min( [1, 3, -2, max( [1.1] min( [-1.1] 4, 1] ) 4 4, 1] ) -2 ) 1.1 ) -1.1 min( [] ) sum( a ) It looks like max. It looks like min. It does not care what order its values are in. It will sum them in a row. It will sum them, high or low. It will sum both ints and floats. It can't make rhymes, but it sums them both: sum( [1, 3, -2, 4, 1] ) 7 sum( [1.1] ) 1.1 S01-8 sum( [5, -1.1] ) 3.9 sum( [] ) 0 String Methods print( str ) We've seen this guy already, so you probably have a pretty good idea of what it does. print takes one argument, a string, and displays that argument on the screen with a newline. Its behavior is one of the few things that's changed radically in Python 3; basically, print in Python 2 is the most irregular verb ever, and Python 3 has redefined it in a fit of Esperanto-like redesign. Regardless, print doesn't have a meaningful return value; it's used solely for its side effects, and it's completely invaluable for interacting with the user of a program and for debugging (you can print the values of your variables while your program is running, among other things). print( "hello world" ) → "hello world" print( str(123) ) → "123" print( "this will be\non two separate lines" ) → "this will be" "on two separate lines" len( str ) The length method also accepts a string argument and just returns the number of characters in the string. Not really much more to say about that... len( "12345" ) 5 len( "onetwothree" ) 11 len( "" ) 0 str[iBegin:iEnd] This one's hard to notate, because the string slice method targets a string without using a dot, and it looks just like an list access. In a way, it is - just like square brackets let you pick out one element of a list, they let you slice out some substring of their target. Given two integer indices, a beginning (starting from zero) and an end (exclusive), the slice method returns a new string containing that sub-chunk of their original target. You can omit either the beginning or the end to zoom all the way to the end of the string: "hello world"[0:5] "hello" "hello world"[3:5] "lo" "hello world"[3:] "lo world" "hello world"[:5] "hello" strString = "hello world" strNew = strString[1:11] print( "j" + strNew ) → "jello world" str.strip( ) Fortunately, application of Python's whitespace stripping method will generally result in the programmer remaining properly garbed, barring unforseen circumstances. What this method does achieve, however, is the S01-9 removal of leading and trailing whitespace from the string to which it's targeted. This doesn't modify the string, but instead returns a new copy with its whitespace removed: " I have space around me\t\n".strip( ) "I have space around me" "I don't".strip( ) "I don't" strOriginal = " Watch closely! " strNewCopy = strOriginal.strip( ) print( "*" + strOriginal + "* *" + strNewCopy + "*" ) → "* Watch closely! * *Watch closely*" str.find( strFind ), str.replace( strFrom, strTo ) I've grouped these together pretty much only because they're found that way in Word - Python strings' find and replace methods don't actually have anything to do with each other. But they're still useful! The former returns the index (starting from zero) of the first occurrence of its argument in its target, or -1 if it's not present: "test".find( "e" ) 1 "testee".find( "e" ) 1 "testiest".find( "est" ) 1 "tastiest".find( "est" ) 5 "toastiest".find( "ost" ) -1 The replace method is a bit more brutal, in that it processes all occurrences of the first argument in its target, and returns a copy in which they've been replaced by the second argument (both of which must be other strings, of course): "test".replace( "e", "" ) "tst" "testee".replace( "e", "" ) "tst" "testiest".replace( "est", "tse" ) "ttseitse" "tastiest".replace( "est", "er" ) "tastier" "toastiest".replace( "roast", "most" ) "toastiest" List Functions a.append( o ), a.pop( ) We've seen two ways so far to get elements into a list (by initializing the list to a particular set of values, or by setting individual indices to values), and one way to get them out again (by reading out individual indices). The append and pop methods give us more ways to accomplish these tasks. append targets an array and takes one argument, any object, and adds that element to the list directly after the last existing element. You can think of this like adding new elements to the end of an array (which, really, is exactly what it's doing). pop does the reverse; it targets a list without taking any arguments, removes the list's last element, and returns it. In both of these cases, "last" means "the element with the greatest index". astrStuff = ["zero", "one", "two"] astrStuff.append( "three" ) print( astrStuff[3] ) astrStuff += ["four"] print( astrStuff.pop( ) ) astrStuff.append( "five" ) for s in astrStuff: S01-10 print( s ) → "three" (from the first print), "four" (from the second), "zero", "one", "two", "three", "five" (all from the third) a.reverse( ) Python is inconsistent about which methods modify their targets and which return copies; I've saved the best for last (see below), but in the meantime, the reverse method modifies its target array in place and... does what you'd expect: ai = [1, 2, 3] for i in ai: print( i ) ai.reverse( ) for i in ai: print( i ) → 1, 2, 3, 3, 2, 1 sorted( a ) The Python sorted function is a wonderful, magical beastie that really embodies the good side of Python. It's built into the language, extremely flexible, efficient, convenient, and fairly transparent. For our purposes, it takes one argument, a list, and returns a sorted copy of that list. You can imagine the sort being performed using the cmp function, which organizes numbers numerically and strings alphabetically; more on that later... for now, check out the examples, and keep that in mind. sorted( [] ) [] sorted( [8, 6, 7, 5, 3, 0, 9] ) [0, 3, 5, 6, 7, 8, 9] sorted( ["one", "two", "three", "four", "five"] ) ["five", "four", "one", "three", "two"] Dictionary Functions hash.keys( ), hash.values( ) These two methods are two sides of the same coin. Each targets a dictionary, takes no arguments, and returns a list containing all of the keys or all of the values in that dictionary, respectively. This is convenient in combination with for loops for accessing each item in a dictionary. But! These lists are not guaranteed to be in any particular order; not alphabetical order, not numerical order, not the order in which you created the dictionary. If you want the keys (or values) in order, you can run the sorted function on the return value of the keys or values functions. hashTest = { "one" : 1, "two" : 2, "three" : 3 } for strKey in hashTest.keys( ): print( strKey ) for strValue in hashTest.values( ): print( strValue ) for strKey in sorted( hashTest.keys( ) ): print( strKey ) for strValue in sorted( hashTest.values( ) ): S01-11 print( strValue ) for strKey in sorted( hashTest.keys( ) ): print( hashTest[strKey] ) → "three", "one", "two", 2, 3, 1, "one", "three", "two", 1, 2, 3, 1, 3, 2 Some Final Bullet Points del [] in len( x ) You've seen all of these repeatedly now, but don't forget about them! They all work for both lists and dictionaries, pretty much as expected, the only caveats being that A) in and len only work for dictionary keys, not values, B) slices only work for lists, not dictionaries, and C) that's all, folks! ai = [1, 2, 3] del ai[1] ai [1, 3] hashTest = {"one" : 1, "two" : 2, "three" : 3} del hashTest["two"] hashTest {"one" : 1, "three" : 3} ai[1] 3 hashTest["one"] 1 ai[1:2] [3] ai[:1] [1] ai[3:] [] 1 in ai True 2 in ai False "one" in hashTest True "two" in hashTest False 3 in hashTest False len( ai ) 2 len( hashTest ) 2 S01-12 Primitive Python Reference Function x.y x = y x in y Arguments x any target y a method x a variable y any expression x any expression y a list or dictionary Effect Meta Operators Runs the method y on the target x Sets x to y Returns y True if x appears in y as a list element or dictionary key Numerical Operators x x x x + * / x x x x += -= *= /= y y y y x and y numbers y y y y x and y numbers x ** y x % y x and y numbers x and y integers Equivalent to x = x + y and so forth x+y x-y x*y x/y x+y x-y x*y x/y xy Remainder of x divided by y Logical Operators not x x and y x or y x == y, x != y x < y, x > y x <= y, x >= y x any expression x and y any expressions x and y numbers or strings The truth value opposite to x True if x and y true True if x or y true True if x and y follow the appropriate numerical or lexical relationship String Operators x + y x * y x and y strings x a string y an integer x + y x and y lists x * y x a list y an integer x a list y an integer The string xy y copies of the string x List Operators del x[y] x[y:z] len( x ) cmp( x, y ) str(x) float(x) Removes the element of x at index y Type-Independent Functions x a string or list y and z integers x a string, list, or dictionary x and y any expressions x any expression x any expression A list containing both x and y's elements A list containing y copies of x's elements The substring/sublist of x starting at y and ending before z The number of characters, elements, or keys in x -1 if x is less than y, 1 if y is less than x, and 0 if they are equal A representation of x as a string A representation of x as a floating point number S01-13 int(x) x any expression A representation of x as an integer, truncated if necessary Numeric Functions abs( x round( min( x max( x sum( x ) x ) ) ) ) x a number x a number x a list of numbers x a list of numbers print( x ) x a string x.strip( ) x a string x.find( y ) x and y strings x.replace( y, z ) x, y, and z strings x.append( y ) x.pop( ) x a list y any object x a list x.reverse( ) x a list sorted( x ) x.sort( ) x a list del x[y] x a dictionary y any object x a dictionary x.keys( ) x.values( ) |x| x rounded up or down (float) Minimum or maximum of x Sum of values in x String Functions Displays x on the screen with a newline A copy of x without preceding or trailing whitespace The index of the first occurrence of y within x, -1 if not present A copy of x with every occurrence of y replaced by z Array Functions Adds y after the last element in x Removes the last element of x Reverses the elements in x sort sorts the elements in x Hash Functions Removes the key/value pair in x with the key y The last element of x sorted returns a copy of x with sorted elements A list of all keys or values in x S01-14