3.1 - 3.5

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Adding, modifying, and removing dictionary entries

dictionaries are mutable *but not the key* *adding to a dictionary* The assignment operator is used to add a new key-value pair to an *already existing dictionary.* prices['banana'] = 1.49 Example: students['John'] = 'A+' modifying a dictionary dict[k] = v: Updates the existing entry dict[k], if dict[k] already exists. Example: students['Jessica'] = 'A+' del keyword is used to remove entries from a dictionary: del prices['papaya'] removes the entry whose key is 'papaya'. del dict[k]: Deletes the entry dict[k]. Example: del students['Rachel']

Set Operations

*Intersection* set.intersection(set_a, set_b, set_c...) Returns a new set containing only the elements in common between set and all provided sets. *Union* set.union(set_a, set_b, set_c...) Returns a new set containing all of the unique elements in all sets. *Difference of sets* set.difference(set_a, set_b, set_c...) Returns a set containing only the elements of set that are not found in any of the provided sets. *symmetric difference* set_a.symmetric_difference(set_b) Returns a set containing only elements that appear in exactly one of set_a or set_b

Common data types

*Numeric types* int and float *Sequence types* string, list, and tuple are all containers for collections of objects ordered by position in the sequence, where the first object has an index of 0 and subsequent elements have indices 1, 2, etc. tuple and list can contain any type strings contains only single-characters *sequence functions* len() indexing using brackets [ ] can be applied to any sequence type. (string, tuple, list) *mapping type* in Python is the dict type. each element of a dict is independent, having no special ordering or relation to other elements. uses key-value pairs

functions and methods useful to lists.

*Operation* *Description* len(list) Find the length of the list. list1 + list2 Produce a new list by concatenating list2 to the end of list1. ex: names = ['rav','chi'] + ['EP'] also name 1 = ['rav','chi'] name 2 = ['EP'] names = name1 + name 2 min(list) Find the element in list with the smallest value. max(list) Find the element in list with the largest value. sum(list) Find the sum of all elements of a list (numbers only). list.index(val) Find the index of the first element in list whose value matches val. user_ages = [ 1, 7, 2, 6, 4 ] user_ages.index(7) --> 1 list.count(val) Count the number of occurrences of the value val in list.

Type conversions

*Type conversions* a conversion of one type to another Ex: int to a float ---> 25 becomes 25.0. float-to-int --> just drops the fraction: 4.9 becomes 4. str() Creates strings str(int/float) will work str(99) --> string '99' int('500') -->integer with a value of 500 float('1.75') --> floating-point value 1.75. *implicit conversion* is a type conversion automatically made by the interpreter, usually between numeric types. result of an arithmetic operation like + or * will be a float only if either operand of the operation is a float. 1 + 2.0 returns a float type.

dictionary

Python container used to describe associative relationships represented by the dict object type associates (or "maps") keys with values key is a term that can be located in a dictionary, such as the word "cat" in the English dictionary key can be any *immutable* type, such as a number, string, or tuple a value can be any type value describes some data associated with a key, such as a definition *Creating dictionary* curly braces { } to surround the key:value pairs that comprise the dictionary contents. players = { } --> empty dictionary players = {'Lionel Messi': 10, 'Cristiano Ronaldo': 7} *Print* print(players) {'Lionel Messi': 10, 'Cristiano Ronaldo': 7} used in place of lists when an associative relationship exists. ex: last names and addresses, car models and price, or student ID number and university email address.

container

a construct used to group related values together and contains references to other objects instead of data

named tuple

allows the programmer to define a new simple data type that consists of named attributes Car = namedtuple('Car',['make','model','price','horsepower','seats']) namedtuple package must be imported to create a new named tuple *from collections import namedtuple* Then the name and attribute names of the named tuple are provided as arguments to the namedtuple constructor. namedtuple() only creates the new simple data type, and does not create new data objects chevy_blazer = Car('Chevrolet', 'Blazer', 32000, 275, 8) data object's attributes can be accessed using dot notation, as in chevy_blazer.price. Named attributes are often much easier for a programmer to work with than indices. Usage: 1) import module from collections import namedtuple 2)Create Car=namedtuple('Car'['make','model','price']) Note: namedtuple() only creates the new simple data type, and does not create new data objects 3) use the named tuple to create a new object. chevy = *Car*('Chevrolet', 'Blazer', 32000) Note: a new data object is not created until Car() is called with appropriate values. 4) print print(chevy) gives Car(make='Chevrolet', model='Blazer', price=32000) 5)data object's attributes can be accessed using dot notation print( chevy.price) 6) mynamedtuple._replace(**kwargs) Return a new instance of the named tuple replacing specified fields with new values lab 3.22 *named tuples are immutable.*

index

an elements position in a list Individual list elements can be accessed using an indexing expression indexing starts with 0 The first element of a list has index 0, the second element has index 1, and so on. ex: my_list[3] Modifying list elements can use this to also update list elements with new values ex: my_list[3] = 19 the index *must be an integer* if a floating point type is used --> runtime error

list

container created by surrounding a sequence of variables or literals with brackets [ ] my_list = [ ]. creates an empty list. No elements in it my_list = [10, 'abc'] my_list = [-100, 'lists are fun'] A list can contain any mix of variable types. Here we have an integer and a string. an item in a list is called an element a list is also a sequence, meaning the contained elements are ordered by position in the list known as the element's index, starting with 0. A list itself is an object, and its value is a sequence of references to the list's elements. useful for reducing the number of variables in a program Instead of having a separate variable for the name of every student in a class, or for every word in an email, a single list can store an entire collection of related variables.

tuple

created by separating elements in parentheses using commas ex:mynumbers = (5, 15, 20) UCI = ('UC Irvine', 8, 'public school') -- mixed data type similar to a list but *immutable* Ex: white_house_coordinates[1] = 50 gives TypeError: 'tuple' object does not support item assignment once created the tuple's elements can not be changed also a sequence type, supporting len(), indexing, and other sequence type functions. printing a tuple always displays surrounding parentheses not as common as list but, useful when a programmer wants to ensure that values do not change. typically used when element position, and not just the relative ordering of elements, is important Ex: when first element should be the latitude, the second element should be the longitude, and the landmark will never move from those coordinates. Index used to access a particular element just like list

adding and removing list elements

lists are mutable A method instructs an object to perform some action, and is executed by specifying the method name following a "." symbol and an object. *append()* - used to add new elements to the *end* of a list list.append(value) Ex: my_list.append('abc') elements are removed using *pop()* or *remove()* list.pop(i): Removes the element at index i from list. Ex: my_list.pop(1) - removes element at index 1 list.remove(v) - Removes the first element whose value is v. Ex: my_list.remove('abc') - removes first 'abc'

accessing dictionary entries

maintain no order ( lists maintain order, index) to access an entry key is specified in brackets [ ] prices = {'apples': 1.99, 'oranges': 1.49} print('The price of apples is', prices['apples']) If no entry with a matching key exists in the dictionary, then a *KeyError* runtime error occurs and the program is terminated. print(prices['lemons']) --> KeyError: 'lemons'

printing a list

names = ['Daniel', 'Roxanna', 'Jean'] print(names) also print (names[0], names[2])

modifying sets

sets are *mutable* *add()* method places a new element into the set *only if it is not already there* Ex: my_set.add('abc') *remove()* and *pop()* methods remove an element from the set. my_set.remove('abc') raises a *Key Error* if value not found in set Ex: my_set.pop() - removes a random element *len()* function to return the number of elements in a set *update()* set1.update(set2) Adds the elements in set2 to set1. mynum = set([1,2,3]) mynum2 = set('abc') mynum2.update(mynum) print (mynum2) -->{'c', 1, 2, 3, 'b', 'a'} mynum3 = {'shy', 'ravi', 'EP'} mynum.update(mynum3) print (mynum)--> {'ravi', 1, 2, 3, 'EP', 'shy'} *clear set* set.clear() Clears all elements from the set. value in set - used to check if a certain value exists in the set

set

unordered collection of unique elements *Set properties* Elements are unordered: Elements in the set do not have a position or index. Elements are unique: No elements in the set share the same value. *Set creation* 1) created using set() function accepts a sequence-type iterable object(list, tuple, string, etc) nums1 = set([1, 2, 3]) -- set contains a list object Note: nums = set(10, 20, 25) --> error set() requires an iterable object like a list to be provided. 2) created using set literal set literal can be written using curly braces { } with commas separating set elements nums2 = { 7, 8, 9 } Note: empty set can only be created using set(). nums = set() set are unordered and have no meaningful position in the collection, the index operator is not valid. nums1[2] to access the element at index 2, is invalid and will produce a runtime error. used to reduce a list of items that potentially contains duplicates into a collection of unique values passing a list into set() will cause any duplicates to be omitted in the created set. first_names = [ 'Harry', 'Hermione', 'Ron', 'Harry'] names_set = set(first_names) print (names_set) --> {'Hermione', 'Harry', 'Ron'} Creating a set removes any duplicate values

Choosing a container type

use a list when data has an order, such as lines of text on a page. (especially if the data can change.) use a tuple instead of a list if the contained data should not change. If order is not important use a dictionary to capture relationships between elements, such as student names and grades.


Set pelajaran terkait

Affordability of Health Goods & Services

View Set

SWO 350-Human Behavior & The Environment I-Part II-"Adolescence"-Chapter 7-"Psychological Development in Adolescence"

View Set

Chapter 10 (Authentication Protocols)

View Set

Better Chinese Book 4: What is Your Name? 你叫什么名字?

View Set