CS521 Final Exam

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

When printing floating-point values, it is desirable to control the number of digits to the right of the decimal point—that is, the precision. How is that done?

variable = 1200356.8796 print(f"With two decimal places: {variable:.2f}")

What is the difference between an algorithm and a program?

There is a difference, and here it is: An algorithm is a description of how a problem can be solved. A program is an implementation of an algorithm in a particular language to run on a particular kind of computer.

Is python an interpreted language?

Yes

In Python, can you do multiple assignments on the same line by separating with commas on both sides.

Yes, an example is: a_int, b_int, c_int = 15, 10, 17

Can the break statement be used to immediately exit the execution of the current loop and skip past all the remaining parts of the loop suite?

Yes, an example is: x_int = 1000 count = 0 while x_int < 100000: if count > 10: break count += 1 print('Thank Goodness you made it out!')

Which provides both the index of the character and the character itself as it steps through the string?

enumerate, an example is: x_string = "Raising Canes" for index, character in enumerate(x_string): print(f'{index:>2d} --> {character}') 0 --> R 1 --> a 2 --> i 3 --> s 4 --> i 5 --> n 6 --> g 7 --> 8 --> C 9 --> a 10 --> n 11 --> e 12 --> s

How would you convert a list and a strin to a tuple?

a_list = [6, 1, 3, 4] a_tuple = tuple(a_list) a_tuple a_string = 'abcd' a_tuple = tuple(a_string) a_tuple

Immutability means?

Cannot be changed

What does for range(1, 5) and for range(5) output?

(1, 2, 3, 4) (0, 1, 2, 3, 4)

How does map work?

(function, iterable, arguement) example: map_result1 = map(lambda x: x + 1, [1,2,3,4,5]) list(map_result1) result = [2, 3, 4, 5, 6] map_result2 = map(lambda x,y: x + y, [1,2,3,4,5], [10,20,30,40,50]) list(map_result2) result = [11, 22, 33, 44, 55]

What operators can be used with a string?

+ (concatenate) and * (paste copy) also can use == and </> (ord aka unicode)

What is a dictionary?

A dictionary in Python is of type dict. A dictionary is a map type, a collection though not a sequence. A map type consists of a set of element pairs. The first element in the pair is the key and the second is the value. x_dict = {'Jimmy': 13, 'Saul': 45, 'Gene': 6}

string methods for: proper case upper case lower case remove whitespace substring search splitting

.title() .upper() .lower() .strip(characters) .find(substring, startingIndex, stoppingIndex) .split(character) .replace(character, replacementCharacter)

What output occurs for the following program on the given input? int_str = 20 first_int = int(int_str) int_str = 10 second_int = int(int_str) tens_count = 0 loop_count = 0 while first_int > 10 and second_int < 20: if first_int == 10 or second_int == 10: tens_count += 1 first_int -= 5 second_int += 5 loop_count += 1 print(tens_count) # Line 1 print(loop_count) # Line 2 print(first_int) # Line 3 print(second_int) # Line 4

1 2 10 20

List the full set of operators for integers and floating-point

1) + addition 2) − subtraction 3) * multiplication 4) / division 5) // quotient 6) % remainder 7) ** exponentiation

What outputs occur for the following program on the given inputs 11 and 12? user_str = 11 OR 12 my_int = int(user_str) count = 0 while my_int > 0: if my_int % 2 == 1: my_int = my_int // 2 else: my_int = my_int - 1 count = count + 1 # Line 2 print(count) # Line 3 print(my_int) # Line 4

4 and 0 5 and 0

If we ran the following code, what will be printed? butter = 46 chicken = 27 gold = 1 total_one = butter + chicken + gold print(total_one) gold = gold + 1 print(total_one)

74 then 74

How do you setup a class?

A class definition starts with the class keyword, followed by the class name. As with all names, the class name must adhere to normal Python naming rules from Module 1Stylewise, Class names traditionally use what is called the CapWords approach. Each word is capitalized, joined together without underscores.The name that follows the keyword is the name of the class and that name becomes associated with a class object, which gets stored in the namespace. After the class name we include, in parentheses, the name of the parent class of our class. Next class, we will cover more on parent and base classes, but for now we always include the class object in parentheses followed by a colon. Following the colon is a suite that defines the class. The suite can contain any relevant Python code, typically methods or vari- able assignments. example: class MyClass(object): pass Once the class is defined, we can inspect what we have made with the Python function dir( ). The function dir( ) lists all of the attributes of the class. Python uses the word "attribute" to indicate both the methods of an object and the names of any values stored in an object. An attribute is a name associated with another object.

Characteristics of a string

A collection type, a special kind called a sequence A sequence type has its collection of objects organized in some order A sequence of characters

What are the characteristics of an expression?

A combination of values and operations that creates a new value, a return value. Entering an expression into a Python shell will return the value and display it.

What is list comprehension?

A comprehension is a compact way to construct a new collection by performing some simple operations on some or all of the elements of another collection. Its origins lie in mathematical set notation. Any comprehension could be implemented using a regular for loop. [ expression for-clause condition ] They are surrounded by either square brackets or braces, which indicates the type of the comprehension and thus the type of the result collection. They have as their first element an expression. This expression is run on every element of the collection being processing and the result of that expression is added as an element to the new collection. They have as their second element a for expression that indicates the collection being processed. They have an optional third element that indicates a condition under which an element from the collection being processed should be run through the expression. One of the restrictions on the expression part of the compreshension is that it must be an expression, i.e. it must not return a value Cannot use if, while or other control statements in the first part of the comprehension. You can write your own function as the expression, as long as it takes the for-clause variable as an argument and returns a value. example: [i for i in range(20) if i % 2 == 0] output = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

What is a dictionary?

A dictionary is a collection, but it is not a sequence. A dictionary is often referred to as a map collection, also sometimes as an associative array. list of pairs, where the first element of each pair is the key and the second element of each pair is the value. A dictionary is designed so that a search for a key, and subsequently its associated value, is very efficient. The word "map" comes from this association: the key maps to the value. All operations on dictionaries are built to work through keys. The data structure is called a "dictionary" because of its similarity to a real dictionary, such as Webster's dictionary. Think of the keys as the words in Webster's dictionary. example: Contacts in a cell phone can be implemented as a Python Dictionary key : Contact Names value : Phone Number contacts = {'bill': '353-1234', 'rich': '269-1234',\ 'jane': '352-1234'} Like a collection of type list, which can be created by either the constructor list() or the square brackets [ ], Dictionaries can be ceatued using the constructor called dict() or the curly braces { } When designating the contents of a dictionary, the individual key-value pairs are separated by a colon : Values may be anything, but keys can only be immutable objects such as integers, strings, or tuples.

What is the difference between a function and a method?

A function is a small program—an encapsulation of an operation. It takes in parameters and returns a value. By providing encapsulation of a task, we can write more readable code. Functions that define the operations that can be done on an object are called methods. When defining a method there are really only a few differences between it and a function: Where a method is defined. An extra argument that is added to every method. Methods are added to a class by defining functions in the suite of a class. By providing these specialized functions in the class, those functions become available to every instance made from the class using the class-instance scope rules we discussed previously. example: def my_method(self, param1): print('\nhello {}'.format(param1)) print('The object that called this method is: {}'.\ format(str(self))) self.instance_attribute = param1

What is a list?

A list in Python is of type list. A list is also a sequence type, like a string, though it can have elements other than characters in the sequences. Lists are indicated with square brackets [ x, y, 1 ] , and its contents are separated by commas. x_list = [4, 3.57, 'abc']

What is an algorithm?

A method, a sequence of steps, that describes how to solve a problem or class of problem.

What is a set?

A set in Python is of type set. A set is a collection of unique elements, similar to a set in mathematics. Sets, like dictionaries, use curly braces, but unlike dictionaries there are no colons. A set supports the mathematical set operations such as union and intersection. x_set = {10, 15, 20}

Characteristics of a set

A set is a collection of objects, regardless of the objects' types. These are the elements or members of the set. Only one copy of any element may exist in the set—a useful characteristic. Set items can appear in a different order every time you use them, thus it is, like a dictionary, not a sequence. A set with no elements is the "empty set," also known as the "null set." A set is an iterable, as are all the collections we have seen. example: a_set = {1, 2, 3, 4} # set constructor. No colons (unlike dictionaries) print(a_set)

What is a subset and what is a super set?

A set is a subset of another set only if every element of the first set is an element of the second set ".<=" operator OR "issubset" method Superset, is the reversed concept, where set A is a superset of set B only if set B is a subset of set A. ">=" operator "issuperset" method

What is a program?

A set of instructions used for problem solving purposes that is executable by computers.

What is a variable?

A variable is a name you create in your program to represent something in a program. This something can be a value, set of data, a file, etc. Once a variable is created, you can store, retrieve and modify the data associated with the variable. The interpreter maintains and keeps a special structure called a namespace to keep the list of names and their associated values.

What are the characteristics of an object?

An identity Some attributes Zero or more names

How do we decide what should or should not be a class in our program?

Context It should be something recognizable to someone familiar with the problem, regardless of their ability to write a program. For example, if the program is a racing game, an object might be a car. A car's actions might include move-forward, turn-right, and report-position. The car object might have attributes such as color, make, or top-speed. By making objects that make sense in the context of the program, it is easier to design the program.

Guidelines for a function are?

Do one thing Readable Not Too Long Reusable Complete Refactoring

What are the characteristics of a statement?

Does not return a value, but does perform some task. Some statements may control the flow of the program, others ask for resources/input. May have a side effect, or a change that results from executing the statement.

Discuss dictionary and set comprehensions

Format: {expression for-clause condition} example: a_dict = {k:v for k,v in enumerate('abcdefg')} a_dict result = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g'} b_list = [(v,k) for v,k in b_dict.items()] sorted(b_list) result = [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)] a_set = {ch for ch in 'it is hot in topeka kansas'} a_set result = {' ', 'a', 'e', 'h', 'i', 'k', 'n', 'o', 'p', 's', 't'}

Think of an example of multiple keyword arguments

Having provided a way to pass multiple positional arguments, Python also provides a way to pass an unknown number of keyword arguments where keyword parameters have not all been provided. In this case, the special parameter requires two asterisks (**). example: def a_function(param1, param2, **param_dict): print(param1, param2, param_dict)

"Hello CS{} this is going to be {}".format(521, 'fun')

Hello CS521 this is going to be fun

Describe some set methods

Intersection: Operation creates a new set of element that are common to both sets "&" operator "intersection" method example: a_set = {'a', 'b', 'c', 'd'} b_set = {'c', 'd', 'e', 'f'} c_set = a_set & b_set OR c_set = a_set.intersection(b_set) print(c_set) {'c', 'd'} Union: Union creates a new set that contains all the elements in both sets "|" operator "union" method example: a_set | b_set # union of all elements a_set.union(b_set) # method approach Difference: Difference creates a new set whose elements are in the first(calling) set and not in the second(argument) set. "-" operator "difference" method example: a_set = {'a','b','c','d'} b_set = {'c','d','e','f'} a_set - b_set # element of a_set, not in b_set OR a_set.difference(b_set) # method approach result = {'a', 'b'} Symmetry: Opposite of intersection, creates a new set of values that are different, not in both, of the two sets. "^" operator "symmetric_difference" method example: a_set = {'a','b','c','d'} b_set = {'c','d','e','f'} a_set ^ b_set OR a_set.symmetric_difference(b_set) # method approach result = {'a', 'b', 'e', 'f'} Add: "add" method example: a_set = {'a','b','c','d'} a_set.add('e') # adds the element to the set a_set.add('fgh') a_set.add(1234) print(a_set) result = {'fgh', 'a', 'c', 1234, 'b', 'e', 'd'} Clear: "clear" method example: a_set = {'a','b','c','d'} a_set.clear() # removes all the elements of the set a_set Remove/Discard: "remove" and "discard" method example: a_set = {'a','b','c','d'} a_set.remove('a') # remove the element if it exists a_set.discard('b') # discard the elemnt if it exists a_set result = {'c', 'd'} Copy: "copy" method a_set = {'a','b','c','d'} b_set = a_set.copy() # returns a shallow copy of the set print(id(a_set)) print(id(b_set)) 2503752643744 2503752644192 Pop: "pop" method example: a_list = ['b', 1, 2, 3, ('a','b'), 'c'] print(a_list.pop()) print(a_list.pop(3)) print(a_list) result = c 3 ['b', 1, 2, ('a', 'b')]

How does python acknowledge scope

LEGB rule: Local Enclosing Global Built-in

What are some operations you can use with a set?

Like lists and dictionaries, sets are a mutable data structure. Though index assignment is not possible on a set (it isn't a sequence), various methods of the set (such as add or remove) change the elements of a set. len( ) Like all collections, you can determine the number of elements in a set using the len function. "in" Is an element in the set? The in operator tests membership and returns a Boolean, True or False, depending on whether the element is or is not a member of the set. "for" Like all collections, you can iterate through the elements of a set using the for statement. The order of the iteration through the objects is not known as sets have no order.

Give the values printed by the following program for each of the labeled lines and answer the associated questions. total_secs = 7845 hours = total_secs // 3600 secs_still_remaining = total_secs % 3600 minutes = secs_still_remaining // 60 secs_finally_remaining = secs_still_remaining % 60 print('Line 1:', hours, type(hours)) # Line 1 print('Line 2:', secs_still_remaining, type(secs_still_remaining)) # Line 2 print('Line 3:', minutes, type(minutes)) # Line 3 print('Line 4:', secs_finally_remaining, type(secs_finally_remaining)) # Line 4 print('Line 5:', float(secs_finally_remaining), type(float(secs_finally_remaining))) # Line 5

Line 1: 2 <class 'int'> Line 2: 645 <class 'int'> Line 3: 10 <class 'int'> Line 4: 45 <class 'int'> Line 5: 45.0 <class 'float'>

Describe some dictionary operators

Most operations should be rather familiar [ ]: indexing using the key as the index value. len( ): the "length" is the number of key-value pairs in the dictionary. in: Boolean test of membership, is the key in the dictionary (not the value) for: iteration through keys in the dictionary.

Can you use .sort on a tuple?

No, a tuple is immutable, you must create a new variable and use the .sorted function example: sorted_tuple = sorted(a_tuple) sorted_tuple

Advantages of using a tuple

Provide assurance that values cannot be changed (not usually a big deal in small programs, but that guarantee is helpful in large codebases). Fastest type to instantiate/create. More idiomatic for some purposes, e.g. an ordered pair of coordinates.

Think of an example of multiple positional alignment

Python allows you to define a special parameter in the parameter list of a function definition that will gather all the extra positional arguments provided by a function call. What makes this parameter special is that it is preceded by an asterisk (*). example: def my_function(param1, param2, *param_rest): print('p1={}, p2={}, p3={}'.format(param1, param2, param_rest)) Placing a single star in front of a parameter name means that any extra position arguments are gathered as a tuple and associated with that parameter. If no extra arguments are passed, then the starred parameter (such as *param_rest) has the value of an empty tuple.

What are python's standard methods

Python reserves some special methods that begin and end with two underscore characters (__). __init__ Method: The first method in our Student class is one of those special Python methods, the constructor __init__. We call the __init__ method a constructor because it is part of the sequence of constructing a new instance of a class. example: class Student(object): """This method initializes the class""" def __init__(self, first='', last='', id=0): print('In the __init__ method') self.first_name_str = first self.last_name_str = last self.id_int = id __str__ Method: As you might guess from the name, it is a method to provide a string that represents the instance. This method is most useful in calls to the print statement, as the print statement attempts to convert any object it is provided into a string. By providing a __str__ method, we can print a representation of our object. For the Student class, the __str__ method creates a single string that brings together the three attributes and returns that string. When a print function is called, the object is "converted" to a string and printed. example: def __str__(self): return 'Value {} is {}'.format(self.the_int,self.parity)

Characteristics of a list

Python's built-in list type notated by "[ ]" is also a collection type. In fact, like strings, lists are a sequence type and are an iterable type. They therefore share some of the characteristics of strings. However, a list differs from a string in two fundamental ways: A list can contain elements other than strings. In fact, a list can contain a sequence of elements of any type, even different typed elements mixed together in the same list. A list is a mutable type. This means that, unlike a string object, a list object can be changed after it is initially created. You can put anything you want into a list, and the items in your list don't have to be related in any particular way. Because a list usually contains more than one element, it's a good idea to make the name of your list plural, such as letters, digits, or names or attach _list to the end of a variable.

List indexing and slicing examples

Same as a string except each element refers to each list element and not each character in a string

What is a triple quote string?

Special kind of string denoted by triple quotes that preserves all the format information of the string. Meaning, if the string spans multiple lines, those new line splits are preserved. Making it easy to capture a whole paragraph as a single string. mantra = """Always look on the bright side of life""" print(mantra) print(type(mantra))

If more than one element appears in a set what happens?

The duplicates are ignored

Tuple operations

The operations familiar from other sequences (lists and strings) are available, except, of course, those operators that violate immutability. Operators such as + (concatenate) and * (repeat) work as before. Slicing also works as before. Membership (in) and for iteration also work on tuples. len, min, max, greater-than (>), less-than (<), sum, and others work the same way. In particular, any comparison operation has the same restrictions for mixed types.

How would you add the methods from a class to a sub-class?

The super() built-in function returns a proxy object (temporary object of the parent class) that allows us to access methods of the base class. Essentially acts as a substitute for declaring the parent class. example: class Animal(object): def __init__(self, Animal): print(Animal, 'is an animal.') class Mammal(Animal): def __init__(self, mammalName): print(mammalName, 'is a warm-blooded animal.') super().__init__(mammalName)

Characteristics of a class

The terms class and instance are important for understanding OOP. They can be a bit tricky at first to understand, especially since different sources (textbook, teachers, websites, etc.) can use different terminology for OOP. This course's viewpoint, a class is a template for making a new object, and that an object made by a class template is called an instance of that class. Analogy: Think of a cookie cutter and a cookie, the cookie cutter is a template for stamping out cookies. Once the template (cookie cutter) is made, we can stamp out any number of cookies, each one formed in the likeness defined by the cutter (template). OOP works similarly. A class is a template for making an instance, and the instance reflects the structure provided by the template, the class. The class can "stamp out" an infinite number of instances, each in the likeness of the class. Example we know: The type int is in fact a template; a general model of the attributes of an integer and the operations that can be performed on an integer. In contrast, the different valued integers 1, 2, 3, 145, 8857485, and so on, are each instances of the int type. Because they are of the same type, each integer instance shares the operations that can be performed on all integers, but each integer instance has local, individual characteristics, that is, their individual value. The class template defines the two major aspects of an instance: the attributes that might be contained in each instance the operations that can be performed on each instance An important note, going back to the cookie cutter example, the operations to be performed on a cookie (instance), such as eat cookie, dunk cookie, etc. are NOT operations that can be performed on the cookie cutter! When we add two int types together, 1 + 2, we're not performing the operation on the type int, int() + int(), but the values.

While loop characteristics

The while loop is sometimes called a "top-tested loop" because there is a Boolean expression to be evaluated at the top of the loop. It is important to remember that the condition is evaluated first before the associated suite is ever executed. If the condition is never True, the loop never executes. Initialization: Outside of the loop and before the loop is entered, the loop-control variable needs to be initialized. What value to initialize the variable requires some consideration. The initial value should (typically) allow the loop to begin (run through the first iteration). This variable's value will control when the loop ends so it is initialized with the condition statement in mind. Control: The condition statement of the while loop needs to be written, and the Boolean expression is typically written in terms of the loop-control variable. Modification: Third, somewhere in the while loop suite, the loop-control variable is modified so that eventually the Boolean expression of the while becomes False so that the loop ends. This often means that the loop-control variable will have a different value in the suite during each iteration of the loop.

What does lambda allow for

There is a special way to define a function called a lambda expression. The word lambda is a kind of homage to the original method used to define functional programming, the lambda calculus. The body of a lambda expression can contain only a single line. The body can only contain an expression (something which returns a value), no statements or other elements. The result of the expression is automatically returned, no return statement is required (or allowed). The form of a lambda is: lambda arg_list: expression example: add_lambda = lambda int1, int2: int1 + int2 map_result1 = map(lambda x: x + 1, [1,2,3,4,5]) list(map_result1) [2, 3, 4, 5, 6]

Which concept allows a programmer to capture a runtime error and give the programmer the option to handle that error. This construct has two suites.

Try-except concept, an example is: print("I swear I'm going to divide by zero!") try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") print("I told you I'd do it") Try-except can be try-except-else-finally Normal flow of Python control enters a try code block. If an error occurs within the try code block, stop executing the code block at the point where the error occurred and abandon the rest of the code block. If unexecuted lines of the try code block remain, they will be ignored. Raise the particular exception for that error that was encountered. Look for an except code block that can handle that exception. That is, an except associated with the particular error name that occurred. If such an except code block is found, move control from the error in the try code block to the beginning of the appropriate except code block. If an error occurs and no appropriate except code block is found (no except is associated with the present error) let Python handle it (i.e. probably crash) If no error occurs in the try code block, that code block finishes, the except code blocks are skipped, and Python continues with normal execution after the try-except construct.

Characteristics of a tuple

Tuples are essentially immutable lists. A tuple shares all the characteristics of a list except those that violate immutability. That is, any function or method that can change a list is not available for tuples. Making it somewhat similiar to a string but can contain elements of any type. Tuples are delimited by parentheses when printed, and like a list its elements are separated by commas. example: x_tuple = (1,2,3)

How do you split lines to more readable ones?

Use "\"

What does the zip operator do?

Zip can create pairs from two parallel sequences. Almost like a zipper to merge multiple sequences into a list of tuples. Zip into tuple or dictionary. a_list = ["John", "Charles", "Mike"] b_list = ["Jenny", "Christy", "Monica"] c_tuple = tuple(zip(a_list, b_list)) print(c_tuple) #tuple(c_tuple) result = (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

Describe how to make a class object private or partially private

_attribute: Only a convention. A way for the programmer to indicate that the variable should be private __attribute: Python interpreter replaces this name with _classname__attribute as a way to make it a bit more private outside of the Class scope When the interpreter is within a Class scope, it will read any call for a private attribute, such as self.__attribute, as self._classname__attribute in the background. Where classname is replaced with the name of the Class' scope it is in (for the above example, NewClass). When the interpreter is outside of a Class scope, we need to define it by self._classname__attribute

How would you swap these two variables? a = 2 b = 3

a, b = b, a

"abcd efgh"[0] and "abcd efgh"[-2]

a, g

How would you find an entry to a dictionary?

aDict = {"a": "12", "b": "4"} adict["a"] returns "12"

a_string = "abcd efgh" a_string[0:4] a_string[5:] a_string[:5] helloString = "Hello World" helloString[::3]

abcd, efgh, abcd_ Slicing allows for a third parameter that specifies the step in the slice. So you can have as many as three numbers separated by a (:) in the operator brackets. hlwl

List some keywords in Python

and, as, assert, break, exec, is, try, del, elif, else, except, in, return, True, from, global, if, input, raise, def, False, not, or, pass, print, continue, for, None, while, with, yield, class, finally, lambda

How would you add a new entry for "barb" to a dictionary?

contacts['barb'] = '271-1234' contacts

What keyword skips some portion of the while/for code block we are executing and has the control flow back to the beginning of the while loop?

continue, an example is: for letter in 'Python': if letter == 'h': continue print('Current Letter:', letter)

What is the format for defining a function

def name(object, attributeOne, attributeN): Body example: def f1 (s1,s2,op=3): if op == 1: temp = s1.intersection(s2) elif op == 2: temp = s1.difference(s2) else: temp = s1.union(s2) return temp set1 = {'ab'} set2 = {'cd'} print(f1(set1,set2)) # Line 1 print(f1(set1,set2,1)) # Line 2 print(f1(set1,set2,2)) # Line 3 result = {'ab', 'cd'} set() {'ab'}

How would you find the identification number of an object

id(object)

The if statement comes with some additional variations that can help decision making even better, what is the format?

if boolean_expression1: # suite1/block1 elif boolean_expression2: # suite2/block2 elif boolean_expression3: # suite3/block3 else: # suiteN/blockN

What are some list methods

index(lookupValue), returns the list index for the value count(lookupValue), returns number of occurances append(listValue), adds a value to the list pop(), removes the element at the end of the list and return that element. The list is shortened by one element. If an index is specified, a.pop(an index) removes the element at that position and returns that item. extend(C), requires a collection C as an argument. The list is extended by adding each individual element of the argument collection C to the end of the list. insert(i, x), inserts an element at a given position. The first argument is the index before which to insert in the list. Thus my list.insert(1, 'a') inserts the 'a' into position 1 of the list, sliding all the rest of the list elements down one (the element at index 1 moves to index 2, the element at index 2 moves to index 3, and so on). remove(x), removes the first element from the list whose value is x. An error results, if there is no such item. The length of the list is decreased by one if successful. sort(), sorts the elements of the list, in place. If sorting a list of lists, only the first element in each list is considered in the comparison operations. Only the order of the list elements is modified (unless already sorted). reverse(), reverses the elements of the list, in place. Only the order of the list elements is modified. join(), takes a list of strings as an argument and concatenates (in order) each of those string into a new string. What is odd about this method is that the calling string is the string that is placed between each string as they are concatenated together. That is, the calling string is used as a separator. example: ':'.join(['a', 'b', 'c']) = 'a:b:c' sorted(), (not a method, a function) will sort any collection. It will: Separate the collection into individual elements. Sort those elements. Return the elements in sorted order as a list.

Describe some dictionary methods

items( ): all the key-value pairs as a list of tuples keys( ): all the keys as a list values( ): all the values as a list

What can be used when a statement is required syntactically but the program requires no action?

pass, an example is: x_int = 11 if x_int != 10: pass if x_int == 11: print('That was weird')

How would you find the third value of the second list in a list of 3 lists

spreadsheet_list = [ ['Name','Age','GPA'], ['Bill', 25, 3.55], ['Rich', 26 , 4.00] ] entry_value = spreadsheet_list[1][2] # [row indx][column indx] entry_value = 3.55

\n and \t do what?

start new line and tab


Kaugnay na mga set ng pag-aaral

Liver Failure and Pancreatitis, NCLEX

View Set

LPIC Level 1 Exam 1 - Init e telinit

View Set

Chapter 5 "Life Insurance Basics" Insurance Questions

View Set

HESI RN Case Study Diabetes Type 1

View Set

Unit 4: National Brokerage: Sale & Lease Contracts:Quiz

View Set

SmartBook Questions Ch. 1 Lecture

View Set